/**
   * Starts the code server with the given command line options. To shut it down, see {@link
   * WebServer#stop}.
   *
   * <p>Only one code server should be started at a time because the GWT compiler uses a lot of
   * static variables.
   */
  public static WebServer start(Options options) throws IOException, UnableToCompleteException {
    if (options.getModuleNames().isEmpty()) {
      throw new IllegalArgumentException("Usage: at least one module must be supplied");
    }

    PrintWriterTreeLogger logger = new PrintWriterTreeLogger();
    logger.setMaxDetail(TreeLogger.Type.INFO);
    Modules modules = new Modules();

    File workDir = ensureWorkDir(options);
    System.out.println("workDir: " + workDir);

    for (String moduleName : options.getModuleNames()) {
      AppSpace appSpace = AppSpace.create(new File(workDir, moduleName));

      Recompiler recompiler = new Recompiler(appSpace, moduleName, options.getSourcePath(), logger);
      modules.addModuleState(new ModuleState(recompiler, logger));
    }

    SourceHandler sourceHandler = new SourceHandler(modules, logger);

    WebServer webServer =
        new WebServer(sourceHandler, modules, options.getBindAddress(), options.getPort(), logger);
    webServer.start();

    return webServer;
  }
Пример #2
0
  @Test
  public void testLoadAllModules() throws IOException {
    File homeDir = MavenTestingUtils.getTestResourceDir("usecases/home");
    BaseHome basehome = new BaseHome(homeDir, homeDir);

    Modules modules = new Modules();
    modules.registerAll(basehome);
    Assert.assertThat("Module count", modules.count(), is(28));
  }
Пример #3
0
  private void sendSourceMap(
      String moduleName, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    long startTime = System.currentTimeMillis();

    ModuleState moduleState = modules.get(moduleName);
    File sourceMap = moduleState.findSourceMap();

    // Stream the file, substituting the sourceroot variable with the filename.
    // (This is more efficient than parsing the file as JSON.)

    // We need to do this at runtime because we don't know what the hostname will be
    // until we get a request. (For example, some people run the Code Server behind
    // a reverse proxy to support https.)

    String sourceRoot =
        String.format(
            "http://%s:%d/sourcemaps/%s/",
            request.getServerName(), request.getServerPort(), moduleName);

    PageUtil.sendTemplateFile(
        "application/json",
        sourceMap,
        "\"" + SOURCEROOT_TEMPLATE_VARIABLE + "\"",
        "\"" + sourceRoot + "\"",
        response);

    long elapsedTime = System.currentTimeMillis() - startTime;

    logger.log(
        TreeLogger.WARN,
        "sent source map for module '" + moduleName + "' in " + elapsedTime + " ms");
  }
Пример #4
0
  @Test
  public void testResolve_ServerHttp() throws IOException {
    File homeDir = MavenTestingUtils.getTestResourceDir("usecases/home");
    BaseHome basehome = new BaseHome(homeDir, homeDir);

    // Register modules
    Modules modules = new Modules();
    modules.registerAll(basehome);
    modules.buildGraph();

    // Enable 2 modules
    modules.enable("server", TEST_SOURCE);
    modules.enable("http", TEST_SOURCE);

    // Collect active module list
    List<Module> active = modules.resolveEnabled();

    // Assert names are correct, and in the right order
    List<String> expectedNames = new ArrayList<>();
    expectedNames.add("base");
    expectedNames.add("xml");
    expectedNames.add("server");
    expectedNames.add("http");

    List<String> actualNames = new ArrayList<>();
    for (Module actual : active) {
      actualNames.add(actual.getName());
    }

    Assert.assertThat(
        "Resolved Names: " + actualNames, actualNames, contains(expectedNames.toArray()));

    // Assert Library List
    List<String> expectedLibs = new ArrayList<>();
    expectedLibs.add("lib/jetty-util-${jetty.version}.jar");
    expectedLibs.add("lib/jetty-io-${jetty.version}.jar");
    expectedLibs.add("lib/jetty-xml-${jetty.version}.jar");
    expectedLibs.add("lib/servlet-api-3.1.jar");
    expectedLibs.add("lib/jetty-schemas-3.1.jar");
    expectedLibs.add("lib/jetty-http-${jetty.version}.jar");
    expectedLibs.add("lib/jetty-continuation-${jetty.version}.jar");
    expectedLibs.add("lib/jetty-server-${jetty.version}.jar");

    List<String> actualLibs = modules.normalizeLibs(active);
    Assert.assertThat("Resolved Libs: " + actualLibs, actualLibs, contains(expectedLibs.toArray()));

    // Assert XML List
    List<String> expectedXmls = new ArrayList<>();
    expectedXmls.add("etc/jetty.xml");
    expectedXmls.add("etc/jetty-http.xml");

    List<String> actualXmls = modules.normalizeXmls(active);
    Assert.assertThat("Resolved XMLs: " + actualXmls, actualXmls, contains(expectedXmls.toArray()));
  }
Пример #5
0
  // makes requests params
  // ie con.query('SELECT * ... WHERE = ?', [requst params], fcn())
  public String makeReqParams(DataObj showObj, List<String> pageParams) {
    StringBuilder reqParams = new StringBuilder(128);
    reqParams.append("[");
    boolean firstIteration = true;
    Modules m = new Modules();
    for (String param : pageParams) {
      if (firstIteration) {
        firstIteration = false;
      } else {
        reqParams.append(",");
      }

      // check if param is a module
      // see how many fkeys this param stands for
      List<Integer> fkIndices;
      if (m.isModule(param)) {
        String tableName = m.modNameToTableName(param);
        fkIndices = showObj.indexForForeignKeysOfType(tableName);
      } else {
        fkIndices = showObj.indexForForeignKeysOfType(param);
      }
      // for every fk, add another req param
      // because each fk will have a ? in the where clause
      if (fkIndices.size() > 0) {
        boolean firstIndex = true;
        for (int fkIndex : fkIndices) {
          if (firstIndex) {
            firstIndex = false;
          } else {
            reqParams.append(" , ");
          }
          reqParams.append("req.params." + param);
        }
      } else {
        reqParams.append("req.params." + param);
      }
    }
    reqParams.append("]");
    return reqParams.toString();
  }
Пример #6
0
  /**
   * Sends an HTTP response containing Java source rendered as HTML. The lines of source that have
   * corresponding JavaScript will be highlighted (as determined by reading the source map).
   */
  private void sendSourceFileAsHtml(
      String moduleName, String sourcePath, BufferedReader lines, HttpServletResponse response)
      throws IOException {

    ReverseSourceMap sourceMap = ReverseSourceMap.load(logger, modules.get(moduleName));

    File sourceFile = new File(sourcePath);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/html");

    HtmlWriter out = new HtmlWriter(response.getWriter());
    out.startTag("html").nl();
    out.startTag("head").nl();
    out.startTag("title").text(sourceFile.getName() + " (GWT Code Server)").endTag("title").nl();
    out.startTag("style").nl();
    out.text(".unused { color: grey; }").nl();
    out.text(".used { color: black; }").nl();
    out.text(".title { margin-top: 0; }").nl();
    out.endTag("style").nl();
    out.endTag("head").nl();
    out.startTag("body").nl();

    out.startTag("a", "href=", ".").text(sourceFile.getParent()).endTag("a").nl();
    out.startTag("h1", "class=", "title").text(sourceFile.getName()).endTag("h1").nl();

    out.startTag("pre", "class=", "unused").nl();
    try {
      int lineNumber = 1;
      for (String line = lines.readLine(); line != null; line = lines.readLine()) {
        if (sourceMap.appearsInJavaScript(sourcePath, lineNumber)) {
          out.startTag("span", "class=", "used").text(line).endTag("span").nl();
        } else {
          out.text(line).nl();
        }
        lineNumber++;
      }

    } finally {
      lines.close();
    }
    out.endTag("pre").nl();

    out.endTag("body").nl();
    out.endTag("html").nl();
  }
Пример #7
0
  /**
   * Sends an HTTP response containing a Java source. It will be sent as plain text by default, or
   * as HTML if the query string is equal to "html".
   */
  private void sendSourceFile(
      String moduleName, String sourcePath, String query, HttpServletResponse response)
      throws IOException {
    ModuleState moduleState = modules.get(moduleName);
    InputStream pageBytes = moduleState.openSourceFile(sourcePath);

    if (pageBytes == null) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      logger.log(TreeLogger.WARN, "unknown source file: " + sourcePath);
      return;
    }

    if (query != null && query.equals("html")) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(pageBytes));
      sendSourceFileAsHtml(moduleName, sourcePath, reader, response);
    } else {
      PageUtil.sendStream("text/plain", pageBytes, response);
    }
  }
Пример #8
0
  @Override
  public void onCreate() {
    super.onCreate();
    AndroidThreeTen.init(this);
    LeakCanary.install(this);

    if (BuildConfig.DEBUG) {
      Timber.plant(new DebugTree());
    } else {
      // TODO Crashlytics.start(this);
      // TODO Timber.plant(new CrashlyticsTree());
    }

    objectGraph = ObjectGraph.create(Modules.list(this));
    objectGraph.inject(this);

    lumberYard.cleanUp();
    Timber.plant(lumberYard.tree());

    registerActivityLifecycleCallbacks(activityHierarchyServer);
  }
  public static void main(String[] args) throws ParseException, IOException {
    Options options = createOptions();
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("?")) {
      new HelpFormatter().printHelp("java " + ShowMoves.class.getName(), options);
      System.exit(1);
    }
    File rootFile = new File(cmd.getOptionValue("root"));
    File movesFile = new File(cmd.getOptionValue("moves"));
    Predicate<ClassName> packageFilter = new PackagePredicate(cmd.getOptionValue("package", ""));
    String groupPrefix = cmd.getOptionValue("group", "");
    File refsFile = cmd.hasOption("refs") ? new File(cmd.getOptionValue("refs")) : null;

    // scan all the pom.xml files
    Modules modules = new Modules();
    modules.scan(rootFile, groupPrefix);

    // load the moves and refs files
    ClassLocations moves = ClassLocations.parseFile(movesFile, groupPrefix);
    ClassLocations refs =
        (refsFile != null) ? ClassLocations.parseFile(refsFile, groupPrefix) : null;

    // scan the compiled classes of all the maven targets
    ClassScanner classScanner = new ClassScanner(packageFilter);
    classScanner.scan(modules.getAllModules());
    ClassLocations locations = classScanner.getLocations();
    ClassDependencies dependencies = classScanner.getDependencies();

    // apply the moves file
    locations.moveAll(moves);

    // apply the refs file, if one was specified
    if (refs != null) {
      for (ModuleName moduleName : refs.getAllModules()) {
        ClassName refsName = new ClassName(moduleName + ":" + refsFile);
        locations.add(refsName, moduleName);
        dependencies.add(refsName, refs.getClasses(moduleName));
      }
    }

    // find modules that reference classes they don't have access to
    Map<ModuleName, ListMultimap<ClassName, ClassName>> brokenMap = Maps.newHashMap();
    for (Map.Entry<ClassName, ModuleName> entry : locations.getLocations()) {
      ClassName className = entry.getKey();
      ModuleName moduleName = entry.getValue();
      Set<ClassName> referencedClasses = dependencies.getReferencedClasses(className);

      ListMultimap<ClassName, ClassName> moduleBrokenMap = null;
      for (ClassName referencedClass : referencedClasses) {
        ModuleName referencedModule = locations.getModule(referencedClass);
        if (referencedModule != null && !modules.isDependentOf(moduleName, referencedModule)) {
          if (moduleBrokenMap == null) {
            moduleBrokenMap = brokenMap.get(moduleName);
            if (moduleBrokenMap == null) {
              brokenMap.put(moduleName, moduleBrokenMap = ArrayListMultimap.create());
            }
          }
          moduleBrokenMap.put(className, referencedClass);
        }
      }
    }

    // report broken dependencies
    System.out.println();
    for (ModuleName moduleName : Utils.sorted(brokenMap.keySet())) {
      ListMultimap<ClassName, ClassName> missingMap = brokenMap.get(moduleName);

      System.out.println();
      System.out.println(moduleName.toString(groupPrefix));

      for (ClassName className : Utils.sorted(missingMap.keySet())) {
        System.out.println("  " + className);
        for (ClassName referencedClass : Utils.sorted(missingMap.get(className))) {
          ModuleName referencedModule = locations.getModule(referencedClass);
          System.out.println(
              "    " + referencedClass + " (" + referencedModule.toString(groupPrefix) + ")");
        }
      }
    }
  }
Пример #10
0
 private SourceMap loadSourceMap(String moduleName) {
   ModuleState moduleState = modules.get(moduleName);
   return SourceMap.load(moduleState.findSourceMap());
 }
Пример #11
0
 public void actionPerformed(ActionEvent ae) {
   // Launch viewer (and sub-modules).
   Modules.initialize();
   updateData();
 }
 private void buildObjectGraphAndInject() {
   objectGraph = ObjectGraph.create(Modules.list(this));
   objectGraph.inject(this);
 }
Пример #13
0
  // From a list of params, this method generates the where clause of the SQL
  // statement. ie) select * from table WHERE ____
  public String parsePageParam(DataObj showObj, List<String> getParams) {
    StringBuilder queryParam = new StringBuilder(512);
    boolean firstIteration = true;
    Modules m = new Modules();
    for (String param : getParams) {
      if (firstIteration) {
        firstIteration = false;
      } else {
        queryParam.append(" and ");
      }
      List<Integer> fkIndices = showObj.indexForForeignKeysOfType(param);
      // check if param is a module
      if (m.isModule(param)) {
        String tableName = m.modNameToTableName(param);
        fkIndices = showObj.indexForForeignKeysOfType(tableName);
        if (fkIndices.size() > 0) {
          boolean firstIndex = true;
          for (int fkIndex : fkIndices) {
            if (firstIndex) {
              firstIndex = false;
            } else {
              queryParam.append(" or ");
            }
            String foreignKeyField = showObj.getFieldName(fkIndex);
            queryParam.append(showObj.getName() + "." + foreignKeyField + " = ? ");
          }
        }
        // could not find the foreign key because it isthis object
        else {
          queryParam.append(showObj.getName() + ".ID = ? ");
        }

      }
      // else check if param is a field of dataobj
      else if (showObj.isField(param)) {
        queryParam.append(showObj.getName() + "." + param + " = ? ");
      }
      // else check if param is a foreign key dependency of dataobj
      else if (fkIndices.size() > 0) {
        boolean firstIndex = true;
        for (int fkIndex : fkIndices) {
          if (firstIndex) {
            firstIndex = false;
          } else {
            queryParam.append(" or ");
          }
          String foreignKeyField = showObj.getFieldName(fkIndex);
          queryParam.append(showObj.getName() + "." + foreignKeyField + " = ? ");
        }

      }
      // check if param is the same name as that object.
      // TODO: in this case, it's get by id which has already been
      // generated. either skip this generation or keep it
      // for later to make communication with cordova easier
      else if (showObj.getName().equals(param)) {
        queryParam.append(showObj.getName() + ".ID = ? ");
      }
      // else there is no match. really, this is an error in the config.
      // TODO: have parser check that one of these three conditions is true
      // now, handle it such that set select * from x where true
      else {
        queryParam.append(" true ");
      }
    }
    return queryParam.toString();
  }