You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rave.apache.org by zh...@apache.org on 2011/04/01 02:29:38 UTC
svn commit: r1087520 [7/35] - in
/incubator/rave/donations/ogce-gadget-container: ./ config/
config/shindig-1.1-BETA5/ config/shindig-2.0.0/ db-cleaner/ examples/
examples/src/ examples/src/main/ examples/src/main/java/
examples/src/main/java/cgl/ exam...
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutSuiteJSONWriter.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutSuiteJSONWriter.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutSuiteJSONWriter.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutSuiteJSONWriter.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,98 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.logging.Logger;
+
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+import static javax.ws.rs.core.Response.Status;
+
+import org.apache.commons.io.IOUtils;
+
+import cgl.shindig.layoutmanager.data.Layout;
+import cgl.shindig.layoutmanager.data.LayoutColumn;
+import cgl.shindig.layoutmanager.data.LayoutColumnJSONSerializer;
+import cgl.shindig.layoutmanager.data.LayoutGadget;
+import cgl.shindig.layoutmanager.data.LayoutGadgetJSONSerializer;
+import cgl.shindig.layoutmanager.data.LayoutJSONSerializer;
+import cgl.shindig.layoutmanager.data.LayoutSuite;
+import cgl.shindig.layoutmanager.data.LayoutSuiteJSONSerializer;
+import cgl.shindig.layoutmanager.data.LayoutTab;
+import cgl.shindig.layoutmanager.data.LayoutTabJSONSerializer;
+
+@Provider
+@Produces("application/json")
+public class LayoutSuiteJSONWriter implements MessageBodyWriter<LayoutSuite> {
+ private static Logger logger =
+ Logger.getLogger(LayoutSuiteJSONWriter.class.getName());
+
+ private String jsonRep = null;
+
+ public long getSize(LayoutSuite layoutSuite, Class<?> type,
+ Type genericType, Annotation[] annotations, MediaType mediaType) {
+ logger.info("LayoutSuiteJSONWriter:getSize...");
+ LayoutSuiteJSONSerializer serializer = new LayoutSuiteJSONSerializer();
+ try {
+ if (jsonRep == null)
+ jsonRep = serializer.convertToString(layoutSuite);
+ return jsonRep.getBytes("utf-8").length;
+ } catch(Exception ex) {
+ return -1;
+ }
+ }
+
+ public boolean isWriteable(Class<?> type, Type genericType,
+ Annotation[] annotations, MediaType mediaType) {
+ logger.info("LayoutSuiteJSONWriter:isWriteable...");
+ if ((mediaType.isWildcardType() || mediaType.getType().equals("application")) &&
+ (mediaType.isWildcardSubtype() || mediaType.getSubtype().equals("json")) &&
+ LayoutSuite.class.isAssignableFrom(type)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void writeTo(LayoutSuite layoutSuite, Class<?> type, Type genericType,
+ Annotation[] annotations, MediaType mediaType,
+ MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
+ throws IOException, WebApplicationException{
+ logger.info("LayoutSuiteJSONWriter:writeTo...");
+ if (jsonRep != null) {
+ IOUtils.write(jsonRep, entityStream, "utf-8");
+ jsonRep = null;
+ } else {
+ throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONReader.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONReader.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONReader.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONReader.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,86 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.logging.Logger;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyReader;
+import javax.ws.rs.ext.Provider;
+import static javax.ws.rs.core.Response.Status;
+
+import org.apache.commons.io.IOUtils;
+import org.json.JSONException;
+
+import cgl.shindig.layoutmanager.data.LayoutTab;
+import cgl.shindig.layoutmanager.data.LayoutTabBuilder;
+
+import com.google.inject.Inject;
+
+
+@Provider
+@Consumes("application/json")
+public class LayoutTabJSONReader
+ extends InjectMessageReader
+ implements MessageBodyReader<LayoutTab> {
+
+ public boolean isReadable(Class<?> type,
+ Type genericType, Annotation[] annotations, MediaType mediaType) {
+ if ((mediaType.isWildcardType() || mediaType.getType().equals("application")) &&
+ (mediaType.isWildcardSubtype() || mediaType.getSubtype().equals("json")) &&
+ LayoutTab.class.isAssignableFrom(type)) {
+ inject();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public LayoutTab readFrom(Class<LayoutTab> type, Type genericType,
+ Annotation[] annotations, MediaType mediaType,
+ MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
+ try {
+ String content = IOUtils.toString(entityStream, "utf-8");
+ return layoutTabBuilder.build(content);
+ } catch (JSONException ex) {
+ throw RESTHelper.newBadReqErrorException(ex.getMessage());
+ } catch(Exception ex) {
+ throw RESTHelper.newInternalErrorException(ex.getMessage());
+ }
+ }
+
+ private LayoutTabBuilder layoutTabBuilder;;
+ @Inject
+ public void setLayoutTabBuilder(LayoutTabBuilder layoutTabBuilder) {
+ this.layoutTabBuilder = layoutTabBuilder;
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONWriter.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONWriter.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONWriter.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutTabJSONWriter.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,84 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.logging.Logger;
+
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+import static javax.ws.rs.core.Response.Status;
+
+import org.apache.commons.io.IOUtils;
+
+import cgl.shindig.layoutmanager.data.LayoutTab;
+import cgl.shindig.layoutmanager.data.LayoutTabJSONSerializer;
+
+@Provider
+@Produces("application/json")
+public class LayoutTabJSONWriter implements MessageBodyWriter<LayoutTab> {
+ private String jsonRep = null;
+
+ public long getSize(LayoutTab layoutTab, Class<?> type,
+ Type genericType, Annotation[] annotations, MediaType mediaType) {
+ LayoutTabJSONSerializer serializer = new LayoutTabJSONSerializer();
+ try {
+ if (jsonRep == null)
+ jsonRep = serializer.convertToString(layoutTab);
+ return jsonRep.getBytes("utf-8").length;
+ } catch(Exception ex) {
+ return -1;
+ }
+ }
+
+ public boolean isWriteable(Class<?> type, Type genericType,
+ Annotation[] annotations, MediaType mediaType) {
+ if ((mediaType.isWildcardType() || mediaType.getType().equals("application")) &&
+ (mediaType.isWildcardSubtype() || mediaType.getSubtype().equals("json")) &&
+ LayoutTab.class.isAssignableFrom(type)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void writeTo(LayoutTab layoutTab, Class<?> type, Type genericType,
+ Annotation[] annotations, MediaType mediaType,
+ MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
+ throws IOException, WebApplicationException{
+ if (jsonRep != null) {
+ IOUtils.write(jsonRep, entityStream, "utf-8");
+ jsonRep = null;
+ } else {
+ throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutUpdate.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutUpdate.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutUpdate.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutUpdate.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,87 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import cgl.shindig.usermanage.*;
+
+/** This class retrieves/updates the layout information of a user.
+ * Currently, JSON is used as transmission format.
+ */
+public class LayoutUpdate extends HttpServlet{
+ private static final String signpage = "/www/sign.jsp";
+ private static String fpsignpage = null;
+
+ /* update layout information */
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ response.setContentType("application/json");
+ HttpSession session = request.getSession();
+ Object obj = session.getAttribute("userId");
+ PrintWriter out = response.getWriter();
+ if( obj != null ){
+ String uid = (String)obj;
+ String data = request.getParameter("json");
+ // The default tab must always be the first one
+ data = data.replaceAll("\"activetabidx\":.*?,", "\"activetabidx\":0,");
+ if( data == null ){
+ out.write("{username:\""+uid+"\",error:\"don't receive any data\"}");
+ }else{
+ UserDBMgr.setUILayoutBySN(new UILayout(uid, data));
+ out.write("{username:\""+uid+"\",data:"+data+"}");
+ }
+ }else{//the user has not signed in.
+ if( fpsignpage == null )
+ fpsignpage = request.getContextPath() + signpage;
+ //response.sendRedirect(fpsignpage);
+ out.write("{error: \"not log in\", redirect:\""+fpsignpage+"\"}");
+ }
+ }
+
+ /* retrieves layout information */
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ response.setContentType("application/json");
+ HttpSession session = request.getSession();
+ Object obj = session.getAttribute("userId");
+ PrintWriter out = response.getWriter();
+ if( obj != null ){
+ String uid = (String)obj;
+ UILayout layout = UserDBMgr.getUILayoutBySN(uid);
+ if( layout != null ){
+ out.write("{username:\""+uid+"\",layout:"+layout.getLayout()+"}");
+ }else{
+ out.write("{username:\""+uid+"\",error:"+"\"It seems that your layout info does not exists\"}");
+ }
+ }else{//has not signed in.
+ if( fpsignpage == null )
+ fpsignpage = request.getContextPath() + signpage;
+ //response.sendRedirect(fpsignpage);
+ out.write("{error: \"not log in\", redirect:\""+fpsignpage+"\"}");
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutWebRESTResource.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutWebRESTResource.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutWebRESTResource.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/LayoutWebRESTResource.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,239 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import static javax.ws.rs.core.Response.ResponseBuilder;
+import static javax.ws.rs.core.Response.Status;
+
+import org.json.JSONException;
+
+import cgl.shindig.layoutmanager.LayoutRESTOPException;
+import cgl.shindig.layoutmanager.data.*;
+import cgl.shindig.usermanage.*;
+
+
+/**
+ * This class provides REST interface to manipulate layout data.
+ */
+@Path("web")
+public class LayoutWebRESTResource {
+ private static Logger logger =
+ Logger.getLogger(LayoutWebRESTResource.class.getName());
+
+ private boolean byPassAuthentication = false;
+
+ // ------------------------------------------------------------------------
+ // Helper methods
+ //
+
+ /**
+ * If param name is specified like "?paramname", it means
+ * - the name of the parameter is "paramname"
+ * - the parameter is optional
+ * Without the question mark, the parameter is not optional any more.
+ * If the parameter name itself contains question mark, add a leading
+ * whitespace.
+ */
+ public static boolean isRequiredParam (String encodedName) {
+ if (encodedName == null || encodedName.equals(""))
+ return false; // FIXME: does not make sense to caller maybe.
+ else {
+ if (encodedName.startsWith("?")) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+ }
+ public static String getParamName (String encodedName) {
+ if (encodedName == null || encodedName.equals(""))
+ return encodedName;
+ else {
+ if (encodedName.startsWith("?")) {
+ return encodedName.substring(1).trim();
+ } else {
+ return encodedName.trim();
+ }
+ }
+ }
+
+ public static String getParamName(String encodedName,
+ MultivaluedMap<String, String> paramMap)
+ throws ParameterMissingException {
+ boolean isRequired = isRequiredParam(encodedName);
+ String paramName = getParamName(encodedName);
+ String value = paramMap.getFirst(paramName);
+ if (isRequired && value == null)
+ throw new ParameterMissingException(paramName);
+ else
+ return value;
+ }
+
+ static class ParameterMissingException extends Exception {
+ private String paramName;
+ public ParameterMissingException (String paramName) {
+ this.paramName = paramName;
+ }
+ public String getMessage () {
+ return "Parameter " + paramName + " is missing";
+ }
+ }
+
+ public String toQueryString (String name, String value, boolean encoded)
+ throws UnsupportedEncodingException {
+ if (encoded)
+ return name + "=" + value;
+ else
+ return URLEncoder.encode(name, "utf-8") + "=" +
+ URLEncoder.encode(value, "utf-8");
+ }
+
+ public String multivaluedMap2QueryString (
+ MultivaluedMap<String, String> paramMap)
+ throws UnsupportedEncodingException {
+ StringBuilder sb = new StringBuilder();
+ Set<String> keys = paramMap.keySet();
+ boolean first = true;
+ for (String key : keys) {
+ if (first) first = false;
+ else sb.append("&");
+ String value = paramMap.getFirst(key);
+ sb.append(URLEncoder.encode(key, "utf-8"));
+ sb.append("=");
+ sb.append(URLEncoder.encode(value, "utf-8"));
+ }
+ return sb.toString();
+ }
+
+ // ------------------------------------------------------------------------
+ // Add a gadget
+ //
+ private static final String paramNameAddGadgetName = "gadgetname";
+ private static final String paramNameAddGadgetSpecSrc = "gadgetspecsrc";
+ private static final String paramNameAddGadgetRenderSrc = "?gadgetrendersrc";
+ private static final String paramNameAddGadgetId = "?gadgetid";
+ private static final String paramNameAddGadgetUserPrefs = "?gadgetuserprefs";
+ private static final String addGadgetAuthenzAddress = "../www/ishindig.html";
+ private static final String addGadgetNonAuthenzAddress = "../www/sign.jsp";
+
+ @GET
+ @Path("{remainder:.*}")
+ public Response errorRequest () {
+ String errMsg = "You submitted a bad request. " +
+ "Check following items:\n" +
+ " - you have specified the correct HTTP header - Accept\n" +
+ " - the url is correct";
+
+ return RESTHelper.buildResponse(Status.BAD_REQUEST, errMsg);
+ }
+
+ /**
+ * FIXME: currently I don't know how to specify multiple paths in
+ * Annotation Path. In jsr311, it is not clear whether multiple uri
+ * templates in Path is allowed. One workaround is to use regular
+ * expression. However, we will lose some features provided by jsr311
+ * implementation. So I just write one resource method for each uri
+ * template. They all invoke the same internal method.
+ */
+ @GET
+ @Path("users/{userid}/addGadget")
+ public Response addAGadget (
+ @Context HttpServletRequest httpRequest,
+ @Context ServletContext servletContext,
+ @PathParam("userid") String userid,
+ @Context UriInfo uriInfo)
+ throws WebApplicationException {
+ return _addAGadget(httpRequest, servletContext, userid, uriInfo);
+ }
+
+ @GET
+ @Path("addGadget")
+ public Response addAGadget2 (
+ @Context HttpServletRequest httpRequest,
+ @Context ServletContext servletContext,
+ @PathParam("userid") String userid,
+ @Context UriInfo uriInfo)
+ throws WebApplicationException {
+ return _addAGadget(httpRequest, servletContext, userid, uriInfo);
+ }
+
+ private Response _addAGadget (HttpServletRequest httpRequest,
+ ServletContext servletContext,
+ String userid, UriInfo uriInfo)
+ throws WebApplicationException {
+
+ String addGadgetName = "addGadget";
+
+ MultivaluedMap<String, String> queryParamMap = uriInfo.getQueryParameters();
+ try {
+ String gadgetName = getParamName(paramNameAddGadgetName, queryParamMap);
+ String gadgetId = getParamName(paramNameAddGadgetId, queryParamMap);
+ String gadgetSpecSrc = getParamName(paramNameAddGadgetSpecSrc, queryParamMap);
+ String gadgetRenderSrc = getParamName(paramNameAddGadgetRenderSrc, queryParamMap);
+ String gadgetUserPrefs = getParamName(paramNameAddGadgetUserPrefs, queryParamMap);
+
+ StringBuilder redirectionURLSB = new StringBuilder();
+
+ // check whether the user has been authenticated
+ ServletAuthenzResult authenzResult = RESTHelper.authenticate(httpRequest, servletContext);
+ if (authenzResult.isSucc()) {
+ queryParamMap.putSingle("method", addGadgetName);
+ redirectionURLSB.append(addGadgetAuthenzAddress)
+ .append("?")
+ .append(multivaluedMap2QueryString(queryParamMap));
+ } else {
+ redirectionURLSB.append(addGadgetNonAuthenzAddress)
+ .append("?")
+ .append(toQueryString("next",
+ uriInfo.getRequestUri().toString(), false));
+ }
+ return RESTHelper.buildRedirectionResponse(redirectionURLSB.toString());
+ } catch(ParameterMissingException ex) {
+ throw RESTHelper.newBadReqErrorException(ex.getMessage());
+ } catch(UnsupportedEncodingException ex) {
+ throw RESTHelper.newInternalErrorException(ex.getMessage());
+ }
+ }
+
+ @GET
+ @Path("")
+ public String getTestString() {
+ return "java-rs web rest works!!";
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/Logout.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/Logout.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/Logout.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/Logout.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,54 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+/** Handles logout. */
+public class Logout extends HttpServlet{
+ private static final String signpage = "/www/sign.jsp";
+ private static String fpsignpage = null;
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ if( fpsignpage == null )
+ fpsignpage = request.getContextPath() + signpage;
+ logout(request, response);
+ }
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ if( fpsignpage == null )
+ fpsignpage = request.getContextPath() + signpage;
+ logout(request, response);
+ }
+ private void logout(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ HttpSession session = request.getSession();
+ if( session != null ){
+ session.invalidate();
+ }
+ response.sendRedirect(fpsignpage);
+ }
+}
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyMetadata.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyMetadata.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyMetadata.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyMetadata.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,84 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+public class ProxyMetadata extends HttpServlet{
+ private final static String GADGET_SERVER_URL = "http://gf13.ucs.indiana.edu:8079/gadgets/metadata";
+ private final static String GET_PARAM_GADGET_URL_KEY = "url";
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ String url = request.getParameter(GET_PARAM_GADGET_URL_KEY);
+ Result result = new Result();
+ if( url == null ){
+ result.setSucc(false);
+ result.setData("Query string is not well formatted");
+ }else{
+ //fetch(url);
+ result.setSucc(true);
+ }
+ }
+ private String fetch(HttpServletRequest request,
+ HttpServletResponse response,
+ String gadgeturl){
+ String url = GADGET_SERVER_URL + "?" + GET_PARAM_GADGET_URL_KEY +
+ "=" + gadgeturl;
+ String content = "";
+ String contentType = "";
+ //StringRequestEntity requestbody = new StringRequestEntity(content, "", );
+ return "";
+ }
+
+ private void responseGen(HttpServletRequest request, HttpServletResponse responseGen,
+ Result result){
+ }
+
+ private class Result{
+ private boolean succ;
+ //public String INVALID_PARAM
+ private String data;
+ public void setSucc(boolean succ){
+ this.succ = succ;
+ }
+ public boolean getSucc(){
+ return this.succ;
+ }
+ public void setData(String data){
+ this.data = data;
+ }
+ public String getData(){
+ return this.data;
+ }
+ }
+}
+
+class MetadataFetcher{
+}
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyServlet.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyServlet.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyServlet.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ProxyServlet.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,484 @@
+//package net.edwardstx;
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
+import org.apache.commons.httpclient.methods.multipart.FilePart;
+import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
+import org.apache.commons.httpclient.methods.multipart.Part;
+import org.apache.commons.httpclient.methods.multipart.StringPart;
+
+
+public class ProxyServlet extends HttpServlet {
+ /**
+ * Serialization UID.
+ */
+ private static final long serialVersionUID = 1L;
+ /**
+ * Key for redirect location header.
+ */
+ private static final String STRING_LOCATION_HEADER = "Location";
+ /**
+ * Key for content type header.
+ */
+ private static final String STRING_CONTENT_TYPE_HEADER_NAME = "Content-Type";
+
+ /**
+ * Key for content length header.
+ */
+ private static final String STRING_CONTENT_LENGTH_HEADER_NAME = "Content-Length";
+ /**
+ * Key for host header
+ */
+ private static final String STRING_HOST_HEADER_NAME = "Host";
+ /**
+ * The directory to use to temporarily store uploaded files
+ */
+ private static final File FILE_UPLOAD_TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
+
+ // Proxy host params
+ /**
+ * The host to which we are proxying requests
+ */
+ private String stringProxyHost;
+ /**
+ * The port on the proxy host to wihch we are proxying requests. Default value is 80.
+ */
+ private int intProxyPort = 80;
+ /**
+ * The (optional) path on the proxy host to wihch we are proxying requests. Default value is "".
+ */
+ private String stringProxyPath = "";
+ /**
+ * The maximum size for uploaded files in bytes. Default value is 5MB.
+ */
+ private int intMaxFileUploadSize = 5 * 1024 * 1024;
+
+ /**
+ * Initialize the <code>ProxyServlet</code>
+ * @param servletConfig The Servlet configuration passed in by the servlet conatiner
+ */
+ public void init(ServletConfig servletConfig) {
+ // Get the proxy host
+ String stringProxyHostNew = servletConfig.getInitParameter("proxyHost");
+ if(stringProxyHostNew == null || stringProxyHostNew.length() == 0) {
+ throw new IllegalArgumentException("Proxy host not set, please set init-param 'proxyHost' in web.xml");
+ }
+ this.setProxyHost(stringProxyHostNew);
+ // Get the proxy port if specified
+ String stringProxyPortNew = servletConfig.getInitParameter("proxyPort");
+ if(stringProxyPortNew != null && stringProxyPortNew.length() > 0) {
+ this.setProxyPort(Integer.parseInt(stringProxyPortNew));
+ }
+ // Get the proxy path if specified
+ String stringProxyPathNew = servletConfig.getInitParameter("proxyPath");
+ if(stringProxyPathNew != null && stringProxyPathNew.length() > 0) {
+ this.setProxyPath(stringProxyPathNew);
+ }
+ // Get the maximum file upload size if specified
+ String stringMaxFileUploadSize = servletConfig.getInitParameter("maxFileUploadSize");
+ if(stringMaxFileUploadSize != null && stringMaxFileUploadSize.length() > 0) {
+ this.setMaxFileUploadSize(Integer.parseInt(stringMaxFileUploadSize));
+ }
+ }
+/*
+ {context:{}, gadgets:[{url:"http://www.labpixies.com/campaigns/todo/todo.xml", language:"en", country:"US"}]}
+ */
+ /**
+ * Performs an HTTP GET request
+ * @param httpServletRequest The {@link HttpServletRequest} object passed
+ * in by the servlet engine representing the
+ * client request to be proxied
+ * @param httpServletResponse The {@link HttpServletResponse} object by which
+ * we can send a proxied response to the client
+ */
+ public void doGet (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
+ throws IOException, ServletException {
+ // Create a GET request
+ GetMethod getMethodProxyRequest = new GetMethod(this.getProxyURL(httpServletRequest));
+ // Forward the request headers
+ setProxyRequestHeaders(httpServletRequest, getMethodProxyRequest);
+ // Execute the proxy request
+ this.executeProxyRequest(getMethodProxyRequest, httpServletRequest, httpServletResponse);
+ }
+
+ /**
+ * Performs an HTTP POST request
+ * @param httpServletRequest The {@link HttpServletRequest} object passed
+ * in by the servlet engine representing the
+ * client request to be proxied
+ * @param httpServletResponse The {@link HttpServletResponse} object by which
+ * we can send a proxied response to the client
+ */
+ public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
+ throws IOException, ServletException {
+ // Create a standard POST request
+ String url = this.getProxyURL(httpServletRequest);
+ PostMethod postMethodProxyRequest = new PostMethod(url);
+ System.out.println("url:" + url+"|");
+
+ // Forward the request headers
+ setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
+ // Check if this is a mulitpart (file upload) POST
+ if(ServletFileUpload.isMultipartContent(httpServletRequest)) {
+ this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
+ } else {
+ this.processPostBody(postMethodProxyRequest, httpServletRequest);
+ }
+ // Execute the proxy request
+ this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
+ }
+
+ protected void processPostBody (PostMethod postMethodProxyRequest,
+ HttpServletRequest httpServletRequest) {
+ setupPostBody(postMethodProxyRequest, httpServletRequest);
+ }
+
+ /**
+ * Sets up the given {@link PostMethod} to send the same multipart POST
+ * data as was sent in the given {@link HttpServletRequest}
+ * @param postMethodProxyRequest The {@link PostMethod} that we are
+ * configuring to send a multipart POST request
+ * @param httpServletRequest The {@link HttpServletRequest} that contains
+ * the mutlipart POST data to be sent via the {@link PostMethod}
+ */
+ @SuppressWarnings("unchecked")
+ private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
+ throws ServletException {
+ // Create a factory for disk-based file items
+ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
+ // Set factory constraints
+ diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
+ diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
+ // Create a new file upload handler
+ ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
+ // Parse the request
+ try {
+ // Get the multipart items as a list
+ List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
+ // Create a list to hold all of the parts
+ List<Part> listParts = new ArrayList<Part>();
+ // Iterate the multipart items list
+ for(FileItem fileItemCurrent : listFileItems) {
+ // If the current item is a form field, then create a string part
+ if (fileItemCurrent.isFormField()) {
+ StringPart stringPart = new StringPart(
+ fileItemCurrent.getFieldName(), // The field name
+ fileItemCurrent.getString() // The field value
+ );
+ // Add the part to the list
+ listParts.add(stringPart);
+ } else {
+ // The item is a file upload, so we create a FilePart
+ FilePart filePart = new FilePart(
+ fileItemCurrent.getFieldName(), // The field name
+ new ByteArrayPartSource(
+ fileItemCurrent.getName(), // The uploaded file name
+ fileItemCurrent.get() // The uploaded file contents
+ )
+ );
+ // Add the part to the list
+ listParts.add(filePart);
+ }
+ }
+ MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
+ listParts.toArray(new Part[] {}),
+ postMethodProxyRequest.getParams()
+ );
+ postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
+ // The current content-type header (received from the client) IS of
+ // type "multipart/form-data", but the content-type header also
+ // contains the chunk boundary string of the chunks. Currently, this
+ // header is using the boundary of the client request, since we
+ // blindly copied all headers from the client request to the proxy
+ // request. However, we are creating a new request with a new chunk
+ // boundary string, so it is necessary that we re-set the
+ // content-type string to reflect the new chunk boundary string
+ postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
+ } catch (FileUploadException fileUploadException) {
+ throw new ServletException(fileUploadException);
+ }
+ }
+
+ /**
+ * Sets up the given {@link PostMethod} to send the same standard POST
+ * data as was sent in the given {@link HttpServletRequest}
+ * @param postMethodProxyRequest The {@link PostMethod} that we are
+ * configuring to send a standard POST request
+ * @param httpServletRequest The {@link HttpServletRequest} that contains
+ * the POST data to be sent via the {@link PostMethod}
+ */
+ @SuppressWarnings("unchecked")
+ protected void handleStandardPost(PostMethod postMethodProxyRequest,
+ HttpServletRequest httpServletRequest) {
+ // Get the client POST data as a Map
+ Map<String, String[]> mapPostParameters = (Map<String,String[]>) httpServletRequest.getParameterMap();
+ // Create a List to hold the NameValuePairs to be passed to the PostMethod
+ List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
+ // Iterate the parameter names
+ for(String stringParameterName : mapPostParameters.keySet()) {
+ // Iterate the values for each parameter name
+ String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
+ for(String stringParamterValue : stringArrayParameterValues) {
+ // Create a NameValuePair and store in list
+ NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
+ listNameValuePairs.add(nameValuePair);
+ }
+ }
+ // Set the proxy request POST data
+ postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] { }));
+ }
+
+ /**
+ * This method is added by Zhenhua Guo.
+ * Functionality of this method is almost the same as that of method
+ * handleStandardPost.
+ * However, the post body in the original request possibly is not a list of
+ * name/value pairs.
+ * Note: as said in servlet docs, to read inputstream and getParameter may
+ * interfere with each other.
+ */
+ @SuppressWarnings("unchecked")
+ protected void setupPostBody(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {
+ int defaultlen = 256;
+ int len = httpServletRequest.getContentLength();
+ StringBuilder body ;
+ if( len != -1 )
+ body = new StringBuilder(len);
+ else
+ body = new StringBuilder(256);
+
+ try{
+ BufferedInputStream bis = new BufferedInputStream(httpServletRequest.getInputStream());
+ int intNextByte;
+ if( bis != null ){
+ while ( ( intNextByte = bis.read() ) != -1 ) {
+ body.append((char)intNextByte);
+ }
+ }
+ }catch(Exception e){
+ System.out.println("exception in setupPostBody:" + e);
+ }
+ // Set the proxy request POST data
+ System.out.println("post body:" + body.toString());
+ postMethodProxyRequest.setRequestBody(body.toString());
+ }
+
+ /**
+ * Executes the {@link HttpMethod} passed in and sends the proxy response
+ * back to the client via the given {@link HttpServletResponse}
+ * @param httpMethodProxyRequest An object representing the proxy request to be made
+ * @param httpServletResponse An object by which we can send the proxied
+ * response back to the client
+ * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
+ * @throws ServletException Can be thrown to indicate that another error has occurred
+ */
+ private void executeProxyRequest(
+ HttpMethod httpMethodProxyRequest,
+ HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse)
+ throws IOException, ServletException {
+ // Create a default HttpClient
+ HttpClient httpClient = new HttpClient();
+ if (httpMethodProxyRequest instanceof GetMethod)
+ httpMethodProxyRequest.setFollowRedirects(true);
+ else
+ httpMethodProxyRequest.setFollowRedirects(false);
+
+ // Execute the request
+ int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
+
+ // Check if the proxy response is a redirect
+ // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
+ // Hooray for open source software
+ if(intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
+ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
+ String stringStatusCode = Integer.toString(intProxyResponseCode);
+ String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
+ if(stringLocation == null) {
+ throw new ServletException("Recieved status code: " + stringStatusCode
+ + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
+ }
+ // Modify the redirect to go to this proxy servlet rather that the proxied host
+ String stringMyHostName = httpServletRequest.getServerName();
+ if(httpServletRequest.getServerPort() != 80) {
+ stringMyHostName += ":" + httpServletRequest.getServerPort();
+ }
+ stringMyHostName += httpServletRequest.getContextPath();
+ httpServletResponse.sendRedirect(stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
+ return;
+ } else if(intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
+ // 304 needs special handling. See:
+ // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
+ // We get a 304 whenever passed an 'If-Modified-Since'
+ // header and the data on disk has not changed; server
+ // responds w/ a 304 saying I'm not going to send the
+ // body because the file has not changed.
+ httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
+ httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+ return;
+ }
+
+ // Pass the response code back to the client
+ httpServletResponse.setStatus(intProxyResponseCode);
+
+ // Pass response headers back to the client
+ Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
+ for(Header header : headerArrayResponse) {
+ if (header.getName().equals("Transfer-Encoding") &&
+ header.getValue().equals("chunked"))
+ continue;
+ httpServletResponse.setHeader(header.getName(), header.getValue());
+ }
+
+ // Send the content to the client
+ InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
+ BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
+ OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
+ int intNextByte;
+ while ( ( intNextByte = bufferedInputStream.read() ) != -1 ) {
+ outputStreamClientResponse.write(intNextByte);
+ }
+ }
+
+ public String getServletInfo() {
+ return "Jason's Proxy Servlet";
+ }
+
+ /**
+ * Retreives all of the headers from the servlet request and sets them on
+ * the proxy request
+ *
+ * @param httpServletRequest The request object representing the client's
+ * request to the servlet engine
+ * @param httpMethodProxyRequest The request that we are about to send to
+ * the proxy host
+ */
+ @SuppressWarnings("unchecked")
+ private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
+ // Get an Enumeration of all of the header names sent by the client
+ Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
+ while(enumerationOfHeaderNames.hasMoreElements()) {
+ String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
+ if(stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME))
+ continue;
+ // As per the Java Servlet API 2.5 documentation:
+ // Some headers, such as Accept-Language can be sent by clients
+ // as several headers each with a different value rather than
+ // sending the header as a comma separated list.
+ // Thus, we get an Enumeration of the header values sent by the client
+ Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
+ while(enumerationOfHeaderValues.hasMoreElements()) {
+ String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
+ // In case the proxy host is running multiple virtual servers,
+ // rewrite the Host header to ensure that we get content from
+ // the correct virtual server
+ if(stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)){
+ stringHeaderValue = getProxyHostAndPort();
+ }
+ Header header = new Header(stringHeaderName, stringHeaderValue);
+ // Set the same header on the proxy request
+ httpMethodProxyRequest.setRequestHeader(header);
+ }
+ }
+ }
+
+ // Accessors
+ protected String getProxyURL(HttpServletRequest httpServletRequest) {
+ // Set the protocol to HTTP
+ // String stringProxyURL = "http://" + this.getProxyHostAndPort();
+ String stringProxyURL = this.getProxyHostAndPort();
+ // Check if we are proxying to a path other that the document root
+ if(!this.getProxyPath().equalsIgnoreCase("")){
+ stringProxyURL += this.getProxyPath();
+ }
+ // Handle the path given to the servlet
+ if( httpServletRequest.getPathInfo() != null )
+ stringProxyURL += httpServletRequest.getPathInfo();
+ // Handle the query string
+ if(httpServletRequest.getQueryString() != null) {
+ stringProxyURL += "?" + httpServletRequest.getQueryString();
+ }
+ return stringProxyURL;
+ }
+
+ protected String getProxyHostAndPort() {
+ if(this.getProxyPort() == 80) {
+ return this.getProxyHost();
+ } else {
+ return this.getProxyHost() + ":" + this.getProxyPort();
+ }
+ }
+
+ protected String getProxyHost() {
+ return this.stringProxyHost;
+ }
+ protected void setProxyHost(String stringProxyHostNew) {
+ this.stringProxyHost = stringProxyHostNew;
+ }
+ protected int getProxyPort() {
+ return this.intProxyPort;
+ }
+ protected void setProxyPort(int intProxyPortNew) {
+ this.intProxyPort = intProxyPortNew;
+ }
+ protected String getProxyPath() {
+ return this.stringProxyPath;
+ }
+ protected void setProxyPath(String stringProxyPathNew) {
+ this.stringProxyPath = stringProxyPathNew;
+ }
+ private int getMaxFileUploadSize() {
+ return this.intMaxFileUploadSize;
+ }
+ private void setMaxFileUploadSize(int intMaxFileUploadSizeNew) {
+ this.intMaxFileUploadSize = intMaxFileUploadSizeNew;
+ }
+}
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/RESTHelper.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/RESTHelper.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/RESTHelper.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/RESTHelper.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,153 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import cgl.shindig.InjectedServlet;
+
+import com.google.inject.Singleton;
+
+import static javax.ws.rs.core.Response.ResponseBuilder;
+import static javax.ws.rs.core.Response.Status;
+
+/**
+ * @author gerald
+ *
+ */
+@Singleton
+public class RESTHelper {
+ public static WebApplicationException newAuthenzException() {
+ String errorMsg = "You have not been authenticated. Make sure you log in first.";
+ return newErrorException(Status.UNAUTHORIZED, errorMsg);
+ }
+
+ public static WebApplicationException newBadReqErrorException(String message) {
+ return newErrorException(Status.BAD_REQUEST, message);
+ }
+
+ public static WebApplicationException newInternalErrorException(String message) {
+ return newErrorException(Status.INTERNAL_SERVER_ERROR, message);
+ }
+
+ public static WebApplicationException newBadReqErrorException(String message, String mimeType) {
+ return newErrorException(Status.BAD_REQUEST, message, mimeType);
+ }
+
+ private static WebApplicationException newErrorException(Status statusCode, String message) {
+ return newErrorException(statusCode, message, MediaType.TEXT_PLAIN);
+ }
+
+ private static WebApplicationException newErrorException(Status statusCode, String message, String mimeType) {
+ ResponseBuilder responseBuilder = Response.status(statusCode);
+ if (mimeType != null)
+ responseBuilder.type(mimeType);
+ responseBuilder.entity(message);
+ Response response = responseBuilder.build();
+ WebApplicationException webAPPEx = new WebApplicationException(response);
+ return webAPPEx;
+ }
+
+ public static ServletAuthenzResult authenticate (
+ HttpServletRequest httpRequest, ServletContext servletContext) {
+ ServletAuthenzResult result = null;
+ try {
+ result = InjectedServlet.getInstance(ServletAuthenzResult.class, servletContext);
+ } catch(Exception ex) {
+ // TODO: needs more graceful solution, rather than return null?
+ ex.printStackTrace();
+ return null;
+ }
+ // ServletAuthenzResult result = new ServletAuthenzResult();
+ result.authenticate(httpRequest);
+ return result;
+ }
+
+ public static Response buildOkResponse(Object obj) {
+ return buildResponse(Status.OK, obj);
+ }
+
+ /**
+ * Don't set mime type.
+ *
+ * @param obj
+ * @return
+ */
+ public static Response buildOkResponse(Object obj, String mimeType) {
+ ResponseBuilder responseBuilder = Response.status(Status.OK);
+ responseBuilder.entity(obj);
+ if (mimeType != null)
+ responseBuilder.type(mimeType);
+ return responseBuilder.build();
+ }
+
+ /*
+ public static Response buildErrorResponse() {
+ ResponseBuilder responseBuilder = Response.status(Status.INTERNAL_SERVER_ERROR);
+ return responseBuilder.build();
+ }
+ */
+
+ /**
+ * Build a response.
+ * Don't set mime type unless msg is a string.
+ *
+ * @param statusCode
+ * @param msg
+ * @return
+ */
+ public static Response buildResponse(Status statusCode, Object msg) {
+ ResponseBuilder responseBuilder = Response.status(statusCode);
+ responseBuilder.entity(msg);
+ if (String.class.isAssignableFrom(msg.getClass())) {
+ responseBuilder.type(MediaType.TEXT_PLAIN);
+ }
+ return responseBuilder.build();
+ }
+
+ public static Response buildRedirectionResponse(String uri) {
+ try {
+ ResponseBuilder builder =
+ // Response.temporaryRedirect(new URL(uri).toURI());
+ Response.temporaryRedirect(new URI(uri));
+ return builder.build();
+ } /*catch(MalformedURLException ex) {
+ String errMsg = "Redirection URL is not correct. " +
+ ex.getMessage();
+ return buildResponse(Status.INTERNAL_SERVER_ERROR, errMsg);
+ } */ catch(URISyntaxException ex) {
+ String errMsg = "Redirection URL is not correct. " +
+ ex.getMessage();
+ return buildResponse(Status.INTERNAL_SERVER_ERROR, errMsg);
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ServletAuthenzResult.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ServletAuthenzResult.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ServletAuthenzResult.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/ServletAuthenzResult.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,84 @@
+package cgl.shindig.layoutmanager.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import cgl.shindig.usermanage.servlet.SignInController;
+
+import com.google.inject.Inject;
+
+public class ServletAuthenzResult {
+ boolean succ = false;
+
+ private String username;
+ private static final String keyUserNameInSession = "";
+
+ @Inject
+ private SignInController signInController;
+
+ /**
+ * get the value of username
+ * @return the value of username
+ */
+ public String getUsername(){
+ return this.username;
+ }
+ /**
+ * set a new value to username
+ * @param username the new value to be used
+ */
+ public void setUsername(String username) {
+ this.username=username;
+ }
+
+ private final static String keyUserName = "userId";
+
+ public void authenticate (HttpServletRequest request) {
+ username = null;
+ succ = false;
+
+ try {
+ // tried to sign in first
+ signInController.authenzIntoSession(request, null);
+ } catch(Exception ex) {
+ }
+ HttpSession session = request.getSession();
+ if (session == null) {
+ succ = false;
+ } else {
+ Object value = session.getAttribute(keyUserName);
+ if (value != null) {
+ succ = true;
+ username = (String)value;
+ } else {
+ succ = false;
+ }
+ }
+ }
+
+ public boolean isSucc () {
+ return succ;
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/from_shindig.tar.gz
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/from_shindig.tar.gz?rev=1087520&view=auto
==============================================================================
Binary file - no diff available.
Propchange: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/layoutmanager/servlet/from_shindig.tar.gz
------------------------------------------------------------------------------
svn:mime-type = application/octet-stream
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/opensocial/GadgetContainerOSModule.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/opensocial/GadgetContainerOSModule.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/opensocial/GadgetContainerOSModule.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/opensocial/GadgetContainerOSModule.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+package cgl.shindig.opensocial;
+
+import org.apache.shindig.social.opensocial.oauth.OAuthDataStore;
+import org.apache.shindig.social.opensocial.spi.ActivityService;
+import org.apache.shindig.social.opensocial.spi.AlbumService;
+import org.apache.shindig.social.opensocial.spi.AppDataService;
+import org.apache.shindig.social.opensocial.spi.MediaItemService;
+import org.apache.shindig.social.opensocial.spi.MessageService;
+import org.apache.shindig.social.opensocial.spi.PersonService;
+import org.apache.shindig.social.sample.oauth.SampleOAuthDataStore;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.name.Names;
+
+/**
+ * Provides bindings for sample-only implementations of social API
+ * classes. This class should never be used in production deployments,
+ * but does provide a good overview of the pieces of Shindig that require
+ * custom container implementations.
+ */
+public class GadgetContainerOSModule extends AbstractModule {
+
+ @Override
+ protected void configure() {
+ bind(String.class).annotatedWith(Names.named("shindig.canonical.json.db"))
+ .toInstance("sampledata/canonicaldb.json");
+ bind(ActivityService.class).to(GadgetContainerOpensocialService.class);
+ bind(AlbumService.class).to(GadgetContainerOpensocialService.class);
+ bind(MediaItemService.class).to(GadgetContainerOpensocialService.class);
+ bind(AppDataService.class).to(GadgetContainerOpensocialService.class);
+ bind(PersonService.class).to(GadgetContainerOpensocialService.class);
+ bind(MessageService.class).to(GadgetContainerOpensocialService.class);
+ bind(OAuthDataStore.class).to(SampleOAuthDataStore.class);
+ }
+}