Example #1
0
 public String generateInterfaceScriptAngular(String csp, String scriptName) {
   RemoteRequestProxy module;
   try {
     module = RemoteRequestProxy.getModule(scriptName, null, null);
   } catch (ClassNotFoundException ignore) {
     logger.log(Level.SEVERE, ignore.toString());
     return "";
   }
   StringBuilder buffer = new StringBuilder();
   // defines the java classes in the global context
   for (Method method : module.getMethodList()) {
     String methodName = method.getName();
     // Is it on the list of banned names
     if (Json.isReserved(methodName)) continue;
     Class<?>[] paramTypes = method.getParameterTypes();
     // Create the function definition
     buffer.append("     " + methodName + ": function(  ");
     for (int j = 0; j < paramTypes.length; j++) buffer.append("p").append(j).append(", ");
     buffer.setLength(buffer.length() - 2);
     buffer.append(") {\n  return this._execute('");
     buffer.append(scriptName);
     buffer.append("', '");
     buffer.append(methodName);
     buffer.append("\', arguments); },\n");
   }
   return buffer.toString();
 }
Example #2
0
 public String generateInterfaceScript(String csp, String scriptName) {
   RemoteRequestProxy module;
   try {
     module = RemoteRequestProxy.getModule(scriptName, null, null);
   } catch (ClassNotFoundException ignore) {
     logger.log(Level.SEVERE, ignore.toString());
     return "";
   }
   StringBuilder buffer = new StringBuilder();
   // defines the java classes in the global context
   buffer.append(
       "\n(function() {  var _ = window; if (_." + scriptName + " == undefined) {\n    var p;");
   buffer.append("p = {}; p._path = '" + csp + "';\n");
   for (Method method : module.getMethodList()) {
     String methodName = method.getName();
     // Is it on the list of banned names
     if (Json.isReserved(methodName)) continue;
     Class<?>[] paramTypes = method.getParameterTypes();
     // Create the function definition
     buffer.append("p." + methodName + " = function(  ");
     for (int j = 0; j < paramTypes.length; j++) buffer.append("p").append(j).append(", ");
     buffer.setLength(buffer.length() - 2);
     buffer.append(") {\n  return brijj._execute(p._path, '");
     buffer.append(scriptName);
     buffer.append("', '");
     buffer.append(methodName);
     buffer.append("\', arguments); };\n");
   }
   buffer.append("    _." + scriptName + "=p; } })();\n");
   return buffer.toString();
 }
Example #3
0
  public void doEngine(HttpServletRequest req, HttpServletResponse resp, boolean angular)
      throws IOException {
    InputStream raw = null;
    String rsrc = null;
    try {
      // getClass() is incorrect here because then subclasses won't work
      String ss = angular ? "aBrijj.js" : "brijj.js";
      raw = BrijjServlet.class.getResourceAsStream(ss);
      if (raw == null) {
        throw new IOException("Failed to find " + ss);
      }
      rsrc = readAllTextFrom(new InputStreamReader(raw));
    } finally {
      if (raw != null) raw.close();
    }
    rsrc = rsrc.replace("${namespace}", "window.brijj");
    long lastModified;
    URL url = BrijjServlet.class.getResource("brijj.js");
    if ("file".equals(url.getProtocol())) {
      File file = new File(url.getFile());
      lastModified = file.lastModified();
    } else if ("jar".equals(url.getProtocol())) {
      lastModified = System.currentTimeMillis();
    } else lastModified = System.currentTimeMillis();
    resp.setContentType("text/javascript; charset=utf-8");
    resp.setDateHeader("Last-Modified", lastModified);
    resp.setHeader("ETag", "\"" + lastModified + '\"');
    PrintWriter out = resp.getWriter();

    StringBuffer sb = new StringBuffer();
    if (angular) {
      /* FIXME:  This only works for a single Brijj Servlet */
      for (String rpn : RemoteRequestProxy.getProxyNames()) {
        rsrc = rsrc.replace("{{scriptName}}", rpn);
        sb.append(generateInterfaceScriptAngular(req.getContextPath() + req.getServletPath(), rpn));
        sb.append("\n\n");
      }
    } else {
      for (String rpn : RemoteRequestProxy.getProxyNames()) {
        sb.append(generateInterfaceScript(req.getContextPath() + req.getServletPath(), rpn));
        sb.append("\n\n");
      }
    }
    rsrc = rsrc.replace("{{functions}}", sb.toString());
    out.print(rsrc);
  }
Example #4
0
  public Object invoker(String mth, Object[] ov, HttpServletRequest req, HttpServletResponse resp) {
    Object rsp;
    RemoteRequestProxy object = null;
    try {
      String[] smns = mth.split("\\.");
      String clazz = smns[0];
      Object[] rna = findMethod(ov, clazz, smns[1]);
      Method method = (Method) rna[0];
      ov = (Object[]) rna[1];
      if (method == null) {
        throw new IllegalArgumentException("Missing method or missing parameter converters");
      }

      if (method.isAnnotationPresent(PreLogin.class)
          || req.getSession().getAttribute(RemoteRequestProxy.loginAttribute) != null) ;
      else return new NotLoggedIn();

      // Convert all the parameters to the correct types
      int destParamCount = method.getParameterTypes().length;
      Object[] arguments = new Object[destParamCount];
      for (int j = 0; j < destParamCount; j++) {
        Object param = ov[j];
        Type paramType = method.getGenericParameterTypes()[j];
        arguments[j] = Cast.cast(paramType, param);
      }
      object = RemoteRequestProxy.getModule(clazz, req, resp);
      Object res = method.invoke(object, arguments);
      rsp = res;
    } catch (InvocationTargetException itx) {
      rsp = itx.getTargetException();
      if (object != null) object.logError(mth, (Throwable) rsp);
      logger.log(Level.SEVERE, ((Throwable) rsp).getLocalizedMessage());
    } catch (Throwable ex) {
      rsp = ex;
      logger.log(Level.SEVERE, ((Throwable) rsp).getLocalizedMessage());
    }
    if (rsp instanceof BufferedImage) rsp = new FileTransfer((BufferedImage) rsp, "png");
    return rsp;
  }
Example #5
0
 public void doIndex(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   StringBuilder buffer = new StringBuilder();
   buffer.append("<html>\n<head><title>Brijj Test Index</title></head>\n<body>\n");
   buffer.append("<h2>Modules known to Brijj:</h2>\n<ul>\n");
   for (String name : RemoteRequestProxy.getProxyNames()) {
     buffer.append("<li><a href='").append(req.getContextPath() + req.getServletPath());
     buffer.append("/test/").append(name).append("'>").append(name).append("</a></li>\n");
   }
   buffer.append(
       "</ul>\n<hr>Return to <a href=\"demo/index.html\">demo home page</a></body></html>\n");
   resp.setContentType("text/html");
   resp.getWriter().print(buffer.toString());
 }
Example #6
0
 public void passthrough(HttpServletRequest request, HttpServletResponse response, String post)
     throws IOException, ServletException {
   try {
     Object object = RemoteRequestProxy.getModule("SWBrijj", request, response);
     Method m =
         object
             .getClass()
             .getMethod(
                 "passthrough", HttpServletRequest.class, HttpServletResponse.class, String.class);
     m.invoke(object, request, response, post);
   } catch (InvocationTargetException ite) {
     throw new ServletException(ite.getTargetException());
   } catch (Exception ce) {
     throw new ServletException(ce);
   }
 }
Example #7
0
  private Object[] findMethod(Object[] ov, String scriptName, String methodName)
      throws ClassNotFoundException {
    int inputArgCount = ov.length;
    // Get a mutable list of all methods on the type specified by the creator
    RemoteRequestProxy module = RemoteRequestProxy.getModule(scriptName, null, null);
    List<Method> allMethods = new ArrayList<Method>();
    List<Object[]> ovl = new ArrayList<Object[]>();

    for (Method m : module.getMethodList()) { // only use methods with matching
      if (m.getName().equals(methodName)) allMethods.add(m);
    }
    if (allMethods.isEmpty()) {
      // Not even a name match
      throw new IllegalArgumentException("Method name not found: " + methodName);
    }
    // Remove all the methods where we can't convert the parameters
    List<Method> am = new ArrayList<Method>();
    Object[] nov = null;
    allMethodsLoop:
    for (Method m : allMethods) {
      Class<?>[] methodParamTypes = m.getParameterTypes();
      if (inputArgCount == 0 && methodParamTypes.length == 0) {
        am.add(m);
        ovl.add(nov);
        continue;
      }
      // Remove non-varargs methods which declare less params than were passed
      if (!m.isVarArgs() && methodParamTypes.length < inputArgCount) continue allMethodsLoop;
      if (m.isVarArgs()) {
        int z = methodParamTypes.length - 1;
        if (inputArgCount < z) continue allMethodsLoop;
        nov = new Object[z + 1];
        int pc = ov.length - z;
        Object[] va = new Object[pc];
        for (int i = 0; i < z; i++) {
          nov[i] = ov[i];
        }
        for (int i = 0; i < pc; i++) {
          va[i] = ov[z + i];
        }
        // BUG: ov needs to be shortened to length z+1
        // This modified "ov" however, is associated with this method -- and the previos ov is
        // associated with its method
        nov[z] = va;
      } else {
        if (methodParamTypes.length != inputArgCount) continue allMethodsLoop;
        nov = new Object[ov.length];
        for (int i = 0; i < ov.length; i++) nov[i] = ov[i];
      }
      // Remove methods where we can't convert the input
      for (int i = 0; i < methodParamTypes.length; i++) {
        Class<?> methodParamType = methodParamTypes[i];
        Object param = nov[i];
        if (param != null && param.getClass() == FileTransfer.class) {
          param = ((FileTransfer) param).asObject();
          nov[i] = param;
        }
        if (inputArgCount <= i && methodParamType.isPrimitive()) continue allMethodsLoop;
        boolean ok = false;
        try {
          Object zpar = Cast.cast(methodParamType, param);
          nov[i] = zpar;
          ok = true;
        } catch (CastException cx) {
          ok = false;
        }
        if (!ok) continue allMethodsLoop;
      }
      am.add(m);
      ovl.add(nov);
    }
    if (am.isEmpty()) {
      // Not even a name match
      throw new IllegalArgumentException("Method not found: " + methodName);
    } else if (am.size() == 1) {
      return new Object[] {am.get(0), ovl.get(0)};
    } else {
      return new Object[] {am.get(0), ovl.get(0)};
    }
    // throw new IllegalArgumentException("Multiple methods found -- the method mapping is
    // ambiguous");
  }
Example #8
0
 public String generateTestPage(final String root, String scriptName) throws IOException {
   RemoteRequestProxy module;
   try {
     module = RemoteRequestProxy.getModule(scriptName, null, null);
   } catch (ClassNotFoundException ignore) {
     return ignore.toString();
   }
   scriptName = module.getClass().getSimpleName();
   String pg = readAllTextFrom(getClass().getResource("test.html"));
   pg = rp(pg, "base", root);
   pg = rp(pg, "moduleName", module.toString());
   StringBuffer sb = new StringBuffer();
   int ii = 0;
   for (Method method : module.getMethodList()) {
     String methodName = method.getName();
     // Is it on the list of unusable names
     if (Json.isReserved(methodName)) {
       sb.append(
           "<li style='color: #88A;'>"
               + methodName
               + "() is not available because it is a reserved word.</li>\n");
       continue;
     }
     sb.append("<li>\n");
     Documentation doc = method.getAnnotation(Documentation.class);
     if (doc != null) {
       sb.append("<strong>");
       sb.append(doc.text());
       sb.append("</strong><p>");
     }
     sb.append("  " + methodName + '(');
     Annotation[][] eg = method.getParameterAnnotations();
     String[] egs = new String[eg.length];
     for (int k = 0; k < eg.length; k++) {
       Annotation[] egx = eg[k];
       for (Annotation egz : egx) {
         if (egz instanceof Eg) {
           egs[k] = ((Eg) egz).value();
         }
       }
     }
     Class<?>[] paramTypes = method.getParameterTypes();
     String iii = Integer.toString(ii);
     for (int j = 0; j < paramTypes.length; j++) {
       Class<?> paramType = paramTypes[j];
       // The special type that we handle transparently
       String value = "";
       if (egs[j] != null) value = "\"" + Json.escapeJavaScript(egs[j]) + "\"";
       else {
         value =
             paramType == String.class
                 ? "\"\""
                 : paramType == Boolean.class || paramType == Boolean.TYPE
                     ? "true"
                     : paramType == Integer.class
                             || paramType == Integer.TYPE
                             || paramType == Short.class
                             || paramType == Short.TYPE
                             || paramType == Long.class
                             || paramType == Long.TYPE
                             || paramType == Byte.class
                             || paramType == Byte.TYPE
                         ? "0"
                         : paramType == Float.class
                                 || paramType == Float.TYPE
                                 || paramType == Double.class
                                 || paramType == Double.TYPE
                             ? "0.0"
                             : paramType.isArray() || Collection.class.isAssignableFrom(paramType)
                                 ? "[]"
                                 : Map.class.isAssignableFrom(paramType) ? "{}" : "";
       }
       int sz = 20;
       if (value.length() > sz) sz = value.length() + 5;
       String input =
           "    <input class='itext' type='text' size='"
               + sz
               + "' value='"
               + value
               + "' id='p"
               + iii
               + "_"
               + j
               + "' title='Will be converted to: "
               + paramType.getName()
               + "'/>";
       if (paramType == BufferedImage.class || paramType == FileTransfer.class) {
         input = "    <input class='itext' type='file' id='p" + iii + "_" + j + "'/>";
       }
       sb.append(input);
       sb.append(j == paramTypes.length - 1 ? "" : ", \n");
     }
     sb.append("  );\n");
     sb.append("<input class='ibutton' type='button' onclick='");
     sb.append("doClick(\"")
         .append(scriptName)
         .append("\",\"")
         .append(methodName)
         .append("\",")
         .append(iii)
         .append(",")
         .append(Integer.toString(paramTypes.length))
         .append(")'");
     sb.append(" value='Execute' title='Calls ")
         .append(scriptName)
         .append(".")
         .append(methodName)
         .append("().' /><div class=\"output\" id='d")
         .append(iii)
         .append("' class='reply'></div>")
         .append("</li>\n");
     ii++;
   }
   pg = rp(pg, "methods", sb.toString());
   return pg;
 }