List of usage examples for java.lang StringBuilder toString
@Override
@HotSpotIntrinsicCandidate
public String toString()
From source file:it.unibas.spicybenchmark.Main.java
public static void main(String[] args) { try {/*ww w.j a va 2s . c o m*/ String propertiesFile = args[0]; StringBuilder executionTimes = new StringBuilder("--- Execution times: ---\n"); Configuration configuration = DAOConfiguration.loadConfigurationFile(propertiesFile); IDataSourceProxy dataSource = new DAOXsd().loadSchema(configuration.getSchemaAbsolutePath()); LoadXMLFile xmlLoader = new LoadXMLFile(); Date beforeLoadingExpected = new Date(); INode expectedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getExpectedInstanceAbsolutePath()); Date afterLoadingExpected = new Date(); long loadingExpected = afterLoadingExpected.getTime() - beforeLoadingExpected.getTime(); executionTimes.append("Expected Instance loaded: ").append(loadingExpected).append(" ms\n"); INode translatedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getTranslatedInstanceAbsolutePath()); Date afterLoadingTranslated = new Date(); long loadingTranslated = afterLoadingTranslated.getTime() - afterLoadingExpected.getTime(); executionTimes.append("Translated Instance loaded: ").append(loadingTranslated).append(" ms\n"); List<String> exclusionList = new DAOExclusionList().loadExclusionList(dataSource, configuration.getExclusionsFileAbsolutePath()); Date startSpicyTime = new Date(); FeatureCollectionGenerator featureCollectionGenerator = new FeatureCollectionGenerator(); FeatureCollection featureCollection = featureCollectionGenerator.generate(expectedInstanceNode, translatedInstanceNode, exclusionList, dataSource, configuration); EvaluateSimilarity evaluator = new EvaluateSimilarity(); SimilarityResult similarityResult = evaluator.getSimilarityResult(featureCollection); similarityResult .setNumberOfNodesInExpectedInstance(new CalculateSize().getNumberOfNodes(expectedInstanceNode)); similarityResult.setNumberOfNodesInTranslatedInstance( new CalculateSize().getNumberOfNodes(translatedInstanceNode)); Date endSpicyTime = new Date(); long spicyExecTime = endSpicyTime.getTime() - startSpicyTime.getTime(); executionTimes.append("Spicy execution time: ").append(spicyExecTime).append(" ms\n"); if (configuration.isTreeEditDistanceValiente()) { Date startValiente = new Date(); similarityResult .setTreeEditDistanceValiente(new TreeEditDistanceGeneratorSimPack().compute(configuration)); Date stopValiente = new Date(); long valienteExecTime = stopValiente.getTime() - startValiente.getTime(); executionTimes.append("Valiente execution time: ").append(valienteExecTime).append(" ms\n"); } if (configuration.isTreeEditDistanceShasha()) { Date startShasha = new Date(); similarityResult.setTreeEditDistanceShasha( new TreeEditDistanceGenerator().computeTreeEditDistance(featureCollection)); Date stopShasha = new Date(); long shashaExecTime = stopShasha.getTime() - startShasha.getTime(); executionTimes.append("Shasha execution time: ").append(shashaExecTime).append(" ms\n"); } // similarityResult.setTopDownOrderedMaximumSubtree(new TopDownOrderedMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setBottomUpMaximumSubtree(new BottomUpMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setJaccard(new JaccardGenerator().compute(expectedInstanceNode, translatedInstanceNode)); Utility.printFinalLog(similarityResult, configuration, executionTimes.toString()); } catch (DAOException ex) { logger.error(ex); } }
From source file:com.searchcode.app.App.java
public static void main(String[] args) { injector = Guice.createInjector(new InjectorConfig()); int server_port = Helpers.tryParseInt( Properties.getProperties().getProperty(Values.SERVERPORT, Values.DEFAULTSERVERPORT), Values.DEFAULTSERVERPORT);//from w ww . j a v a 2 s . c o m boolean onlyLocalhost = Boolean .parseBoolean(Properties.getProperties().getProperty("only_localhost", "false")); // Database migrations happen before we start databaseMigrations(); LOGGER.info("Starting searchcode server on port " + server_port); Spark.port(server_port); JobService js = injector.getInstance(JobService.class); Repo repo = injector.getInstance(Repo.class); Data data = injector.getInstance(Data.class); Api api = injector.getInstance(Api.class); ApiService apiService = injector.getInstance(ApiService.class); StatsService statsService = new StatsService(); scl = Singleton.getSearchcodeLib(data); js.initialJobs(); Gson gson = new Gson(); Spark.staticFileLocation("/public"); before((request, response) -> { if (onlyLocalhost) { if (!request.ip().equals("127.0.0.1")) { halt(204); } } }); get("/", (req, res) -> { Map<String, Object> map = new HashMap<>(); map.put("repoCount", repo.getRepoCount()); if (req.queryParams().contains("q") && !req.queryParams("q").trim().equals("")) { String query = req.queryParams("q").trim(); int page = 0; if (req.queryParams().contains("p")) { try { page = Integer.parseInt(req.queryParams("p")); page = page > 19 ? 19 : page; } catch (NumberFormatException ex) { page = 0; } } List<String> reposList = new ArrayList<>(); List<String> langsList = new ArrayList<>(); List<String> ownsList = new ArrayList<>(); if (req.queryParams().contains("repo")) { String[] repos = new String[0]; repos = req.queryParamsValues("repo"); if (repos.length != 0) { reposList = Arrays.asList(repos); } } if (req.queryParams().contains("lan")) { String[] langs = new String[0]; langs = req.queryParamsValues("lan"); if (langs.length != 0) { langsList = Arrays.asList(langs); } } if (req.queryParams().contains("own")) { String[] owns = new String[0]; owns = req.queryParamsValues("own"); if (owns.length != 0) { ownsList = Arrays.asList(owns); } } map.put("searchValue", query); map.put("searchResultJson", gson.toJson(new CodePreload(query, page, langsList, reposList, ownsList))); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "search_test.ftl"); } // Totally pointless vanity but lets rotate the image every week int photoId = getWeekOfMonth(); if (photoId <= 0) { photoId = 3; } if (photoId > 4) { photoId = 2; } CodeSearcher cs = new CodeSearcher(); map.put("photoId", photoId); map.put("numDocs", cs.getTotalNumberDocumentsIndexed()); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "index.ftl"); }, new FreeMarkerEngine()); get("/html/", (req, res) -> { CodeSearcher cs = new CodeSearcher(); CodeMatcher cm = new CodeMatcher(data); Map<String, Object> map = new HashMap<>(); map.put("repoCount", repo.getRepoCount()); if (req.queryParams().contains("q")) { String query = req.queryParams("q").trim(); String altquery = query.replaceAll("[^A-Za-z0-9 ]", " ").trim().replaceAll(" +", " "); int page = 0; if (req.queryParams().contains("p")) { try { page = Integer.parseInt(req.queryParams("p")); page = page > 19 ? 19 : page; } catch (NumberFormatException ex) { page = 0; } } String[] repos = new String[0]; String[] langs = new String[0]; String reposFilter = ""; String langsFilter = ""; String reposQueryString = ""; String langsQueryString = ""; if (req.queryParams().contains("repo")) { repos = req.queryParamsValues("repo"); if (repos.length != 0) { List<String> reposList = Arrays.asList(repos).stream() .map((s) -> "reponame:" + QueryParser.escape(s)).collect(Collectors.toList()); reposFilter = " && (" + StringUtils.join(reposList, " || ") + ")"; List<String> reposQueryList = Arrays.asList(repos).stream() .map((s) -> "&repo=" + URLEncoder.encode(s)).collect(Collectors.toList()); reposQueryString = StringUtils.join(reposQueryList, ""); } } if (req.queryParams().contains("lan")) { langs = req.queryParamsValues("lan"); if (langs.length != 0) { List<String> langsList = Arrays.asList(langs).stream() .map((s) -> "languagename:" + QueryParser.escape(s)).collect(Collectors.toList()); langsFilter = " && (" + StringUtils.join(langsList, " || ") + ")"; List<String> langsQueryList = Arrays.asList(langs).stream() .map((s) -> "&lan=" + URLEncoder.encode(s)).collect(Collectors.toList()); langsQueryString = StringUtils.join(langsQueryList, ""); } } // split the query escape it and and it together String cleanQueryString = scl.formatQueryString(query); SearchResult searchResult = cs.search(cleanQueryString + reposFilter + langsFilter, page); searchResult.setCodeResultList(cm.formatResults(searchResult.getCodeResultList(), query, true)); for (CodeFacetRepo f : searchResult.getRepoFacetResults()) { if (Arrays.asList(repos).contains(f.getRepoName())) { f.setSelected(true); } } for (CodeFacetLanguage f : searchResult.getLanguageFacetResults()) { if (Arrays.asList(langs).contains(f.getLanguageName())) { f.setSelected(true); } } map.put("searchValue", query); map.put("searchResult", searchResult); map.put("reposQueryString", reposQueryString); map.put("langsQueryString", langsQueryString); map.put("altQuery", altquery); map.put("isHtml", true); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "searchresults.ftl"); } // Totally pointless vanity but lets rotate the image every week int photoId = getWeekOfMonth(); if (photoId <= 0) { photoId = 3; } if (photoId > 4) { photoId = 2; } map.put("photoId", photoId); map.put("numDocs", cs.getTotalNumberDocumentsIndexed()); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "index.ftl"); }, new FreeMarkerEngine()); /** * Allows one to write literal lucene search queries against the index * TODO This is still very much WIP */ get("/literal/", (req, res) -> { CodeSearcher cs = new CodeSearcher(); CodeMatcher cm = new CodeMatcher(data); Map<String, Object> map = new HashMap<>(); map.put("repoCount", repo.getRepoCount()); if (req.queryParams().contains("q")) { String query = req.queryParams("q").trim(); int page = 0; if (req.queryParams().contains("p")) { try { page = Integer.parseInt(req.queryParams("p")); page = page > 19 ? 19 : page; } catch (NumberFormatException ex) { page = 0; } } String altquery = query.replaceAll("[^A-Za-z0-9 ]", " ").trim().replaceAll(" +", " "); SearchResult searchResult = cs.search(query, page); searchResult.setCodeResultList(cm.formatResults(searchResult.getCodeResultList(), altquery, false)); map.put("searchValue", query); map.put("searchResult", searchResult); map.put("reposQueryString", ""); map.put("langsQueryString", ""); map.put("altQuery", ""); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "searchresults.ftl"); } map.put("numDocs", cs.getTotalNumberDocumentsIndexed()); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "index.ftl"); }, new FreeMarkerEngine()); /** * This is the endpoint used by the frontend. */ get("/api/codesearch/", (req, res) -> { CodeSearcher cs = new CodeSearcher(); CodeMatcher cm = new CodeMatcher(data); if (req.queryParams().contains("q") && req.queryParams("q").trim() != "") { String query = req.queryParams("q").trim(); int page = 0; if (req.queryParams().contains("p")) { try { page = Integer.parseInt(req.queryParams("p")); page = page > 19 ? 19 : page; } catch (NumberFormatException ex) { page = 0; } } String[] repos = new String[0]; String[] langs = new String[0]; String[] owners = new String[0]; String reposFilter = ""; String langsFilter = ""; String ownersFilter = ""; if (req.queryParams().contains("repo")) { repos = req.queryParamsValues("repo"); if (repos.length != 0) { List<String> reposList = Arrays.asList(repos).stream() .map((s) -> "reponame:" + QueryParser.escape(s)).collect(Collectors.toList()); reposFilter = " && (" + StringUtils.join(reposList, " || ") + ")"; } } if (req.queryParams().contains("lan")) { langs = req.queryParamsValues("lan"); if (langs.length != 0) { List<String> langsList = Arrays.asList(langs).stream() .map((s) -> "languagename:" + QueryParser.escape(s)).collect(Collectors.toList()); langsFilter = " && (" + StringUtils.join(langsList, " || ") + ")"; } } if (req.queryParams().contains("own")) { owners = req.queryParamsValues("own"); if (owners.length != 0) { List<String> ownersList = Arrays.asList(owners).stream() .map((s) -> "codeowner:" + QueryParser.escape(s)).collect(Collectors.toList()); ownersFilter = " && (" + StringUtils.join(ownersList, " || ") + ")"; } } // Need to pass in the filters into this query String cacheKey = query + page + reposFilter + langsFilter + ownersFilter; if (cache.containsKey(cacheKey)) { return cache.get(cacheKey); } // split the query escape it and and it together String cleanQueryString = scl.formatQueryString(query); SearchResult searchResult = cs.search(cleanQueryString + reposFilter + langsFilter + ownersFilter, page); searchResult.setCodeResultList(cm.formatResults(searchResult.getCodeResultList(), query, true)); searchResult.setQuery(query); for (String altQuery : scl.generateAltQueries(query)) { searchResult.addAltQuery(altQuery); } // Null out code as it isnt required and there is no point in bloating our ajax requests for (CodeResult codeSearchResult : searchResult.getCodeResultList()) { codeSearchResult.setCode(null); } cache.put(cacheKey, searchResult); return searchResult; } return null; }, new JsonTransformer()); get("/api/repo/add/", "application/json", (request, response) -> { boolean apiEnabled = Boolean .parseBoolean(Properties.getProperties().getProperty("api_enabled", "false")); boolean apiAuth = Boolean .parseBoolean(Properties.getProperties().getProperty("api_key_authentication", "true")); if (!apiEnabled) { return new ApiResponse(false, "API not enabled"); } String publicKey = request.queryParams("pub"); String signedKey = request.queryParams("sig"); String reponames = request.queryParams("reponame"); String repourls = request.queryParams("repourl"); String repotype = request.queryParams("repotype"); String repousername = request.queryParams("repousername"); String repopassword = request.queryParams("repopassword"); String reposource = request.queryParams("reposource"); String repobranch = request.queryParams("repobranch"); if (reponames == null || reponames.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "reponame is a required parameter"); } if (repourls == null || repourls.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "repourl is a required parameter"); } if (repotype == null) { return new ApiResponse(false, "repotype is a required parameter"); } if (repousername == null) { return new ApiResponse(false, "repousername is a required parameter"); } if (repopassword == null) { return new ApiResponse(false, "repopassword is a required parameter"); } if (reposource == null) { return new ApiResponse(false, "reposource is a required parameter"); } if (repobranch == null) { return new ApiResponse(false, "repobranch is a required parameter"); } if (apiAuth) { if (publicKey == null || publicKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "pub is a required parameter"); } if (signedKey == null || signedKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "sig is a required parameter"); } String toValidate = String.format( "pub=%s&reponame=%s&repourl=%s&repotype=%s&repousername=%s&repopassword=%s&reposource=%s&repobranch=%s", URLEncoder.encode(publicKey), URLEncoder.encode(reponames), URLEncoder.encode(repourls), URLEncoder.encode(repotype), URLEncoder.encode(repousername), URLEncoder.encode(repopassword), URLEncoder.encode(reposource), URLEncoder.encode(repobranch)); boolean validRequest = apiService.validateRequest(publicKey, signedKey, toValidate); if (!validRequest) { return new ApiResponse(false, "invalid signed url"); } } // Clean if (repobranch == null || repobranch.trim().equals(Values.EMPTYSTRING)) { repobranch = "master"; } repotype = repotype.trim().toLowerCase(); if (!"git".equals(repotype) && !"svn".equals(repotype)) { repotype = "git"; } RepoResult repoResult = repo.getRepoByName(reponames); if (repoResult != null) { return new ApiResponse(false, "repository name already exists"); } repo.saveRepo(new RepoResult(-1, reponames, repotype, repourls, repousername, repopassword, reposource, repobranch)); return new ApiResponse(true, "added repository successfully"); }, new JsonTransformer()); get("/api/repo/delete/", "application/json", (request, response) -> { boolean apiEnabled = Boolean .parseBoolean(Properties.getProperties().getProperty("api_enabled", "false")); boolean apiAuth = Boolean .parseBoolean(Properties.getProperties().getProperty("api_key_authentication", "true")); if (!apiEnabled) { return new ApiResponse(false, "API not enabled"); } String publicKey = request.queryParams("pub"); String signedKey = request.queryParams("sig"); String reponames = request.queryParams("reponame"); if (reponames == null || reponames.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "reponame is a required parameter"); } if (apiAuth) { if (publicKey == null || publicKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "pub is a required parameter"); } if (signedKey == null || signedKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "sig is a required parameter"); } String toValidate = String.format("pub=%s&reponame=%s", URLEncoder.encode(publicKey), URLEncoder.encode(reponames)); boolean validRequest = apiService.validateRequest(publicKey, signedKey, toValidate); if (!validRequest) { return new ApiResponse(false, "invalid signed url"); } } RepoResult rr = repo.getRepoByName(reponames); if (rr == null) { return new ApiResponse(false, "repository already deleted"); } Singleton.getUniqueDeleteRepoQueue().add(rr); return new ApiResponse(true, "repository queued for deletion"); }, new JsonTransformer()); get("/api/repo/list/", "application/json", (request, response) -> { boolean apiEnabled = Boolean .parseBoolean(Properties.getProperties().getProperty("api_enabled", "false")); boolean apiAuth = Boolean .parseBoolean(Properties.getProperties().getProperty("api_key_authentication", "true")); if (!apiEnabled) { return new ApiResponse(false, "API not enabled"); } String publicKey = request.queryParams("pub"); String signedKey = request.queryParams("sig"); if (apiAuth) { if (publicKey == null || publicKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "pub is a required parameter"); } if (signedKey == null || signedKey.trim().equals(Values.EMPTYSTRING)) { return new ApiResponse(false, "sig is a required parameter"); } String toValidate = String.format("pub=%s", URLEncoder.encode(publicKey)); boolean validRequest = apiService.validateRequest(publicKey, signedKey, toValidate); if (!validRequest) { return new ApiResponse(false, "invalid signed url"); } } List<RepoResult> repoResultList = repo.getAllRepo(); return new RepoResultApiResponse(true, Values.EMPTYSTRING, repoResultList); }, new JsonTransformer()); get("/admin/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } CodeSearcher cs = new CodeSearcher(); Map<String, Object> map = new HashMap<>(); map.put("repoCount", repo.getRepoCount()); map.put("numDocs", cs.getTotalNumberDocumentsIndexed()); map.put("numSearches", statsService.getSearchCount()); map.put("uptime", statsService.getUptime()); // Put all properties here map.put(Values.SQLITEFILE, Properties.getProperties().getProperty(Values.SQLITEFILE, Values.DEFAULTSQLITEFILE)); map.put(Values.SERVERPORT, Properties.getProperties().getProperty(Values.SERVERPORT, Values.DEFAULTSERVERPORT)); map.put(Values.REPOSITORYLOCATION, Properties.getProperties().getProperty(Values.REPOSITORYLOCATION, Values.DEFAULTREPOSITORYLOCATION)); map.put(Values.INDEXLOCATION, Properties.getProperties().getProperty(Values.INDEXLOCATION, Values.DEFAULTINDEXLOCATION)); map.put(Values.FACETSLOCATION, Properties.getProperties().getProperty(Values.FACETSLOCATION, Values.DEFAULTFACETSLOCATION)); map.put(Values.CHECKREPOCHANGES, Properties.getProperties().getProperty(Values.CHECKREPOCHANGES, Values.DEFAULTCHECKREPOCHANGES)); map.put(Values.ONLYLOCALHOST, Properties.getProperties().getProperty(Values.ONLYLOCALHOST, Values.DEFAULTONLYLOCALHOST)); map.put(Values.LOWMEMORY, Properties.getProperties().getProperty(Values.LOWMEMORY, Values.DEFAULTLOWMEMORY)); map.put(Values.SPELLINGCORRECTORSIZE, Properties.getProperties() .getProperty(Values.SPELLINGCORRECTORSIZE, Values.DEFAULTSPELLINGCORRECTORSIZE)); map.put(Values.USESYSTEMGIT, Properties.getProperties().getProperty(Values.USESYSTEMGIT, Values.DEFAULTUSESYSTEMGIT)); map.put(Values.GITBINARYPATH, Properties.getProperties().getProperty(Values.GITBINARYPATH, Values.DEFAULTGITBINARYPATH)); map.put(Values.APIENABLED, Properties.getProperties().getProperty(Values.APIENABLED, Values.DEFAULTAPIENABLED)); map.put(Values.APIKEYAUTH, Properties.getProperties().getProperty(Values.APIKEYAUTH, Values.DEFAULTAPIKEYAUTH)); map.put(Values.SVNBINARYPATH, Properties.getProperties().getProperty(Values.SVNBINARYPATH, Values.DEFAULTSVNBINARYPATH)); map.put(Values.SVNENABLED, Properties.getProperties().getProperty(Values.SVNENABLED, Values.DEFAULTSVNENABLED)); map.put(Values.MAXDOCUMENTQUEUESIZE, Properties.getProperties().getProperty(Values.MAXDOCUMENTQUEUESIZE, Values.DEFAULTMAXDOCUMENTQUEUESIZE)); map.put(Values.MAXDOCUMENTQUEUELINESIZE, Properties.getProperties() .getProperty(Values.MAXDOCUMENTQUEUELINESIZE, Values.DEFAULTMAXDOCUMENTQUEUELINESIZE)); map.put(Values.MAXFILELINEDEPTH, Properties.getProperties().getProperty(Values.MAXFILELINEDEPTH, Values.DEFAULTMAXFILELINEDEPTH)); map.put("deletionQueue", Singleton.getUniqueDeleteRepoQueue().size()); map.put("version", VERSION); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin.ftl"); }, new FreeMarkerEngine()); get("/admin/repo/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } int repoCount = repo.getRepoCount(); String offSet = request.queryParams("offset"); String searchQuery = request.queryParams("q"); int indexOffset = 0; Map<String, Object> map = new HashMap<>(); if (offSet != null) { try { indexOffset = Integer.parseInt(offSet); if (indexOffset > repoCount || indexOffset < 0) { indexOffset = 0; } } catch (NumberFormatException ex) { indexOffset = 0; } } if (searchQuery != null) { map.put("repoResults", repo.searchRepo(searchQuery)); } else { map.put("repoResults", repo.getPagedRepo(indexOffset, 100)); } map.put("searchQuery", searchQuery); map.put("hasPrevious", indexOffset > 0); map.put("hasNext", (indexOffset + 100) < repoCount); map.put("previousOffset", "" + (indexOffset - 100)); map.put("nextOffset", "" + (indexOffset + 100)); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin_repo.ftl"); }, new FreeMarkerEngine()); get("/admin/bulk/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin_bulk.ftl"); }, new FreeMarkerEngine()); get("/admin/api/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } Map<String, Object> map = new HashMap<>(); map.put("apiKeys", api.getAllApi()); boolean apiEnabled = Boolean .parseBoolean(Properties.getProperties().getProperty("api_enabled", "false")); boolean apiAuth = Boolean .parseBoolean(Properties.getProperties().getProperty("api_key_authentication", "true")); map.put("apiAuthentication", apiEnabled && apiAuth); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin_api.ftl"); }, new FreeMarkerEngine()); post("/admin/api/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } apiService.createKeys(); response.redirect("/admin/api/"); halt(); return null; }, new FreeMarkerEngine()); get("/admin/api/delete/", "application/json", (request, response) -> { if (getAuthenticatedUser(request) == null || !request.queryParams().contains("publicKey")) { response.redirect("/login/"); halt(); return false; } String publicKey = request.queryParams("publicKey"); apiService.deleteKey(publicKey); return true; }, new JsonTransformer()); get("/admin/settings/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } String[] highlighters = "agate,androidstudio,arta,ascetic,atelier-cave.dark,atelier-cave.light,atelier-dune.dark,atelier-dune.light,atelier-estuary.dark,atelier-estuary.light,atelier-forest.dark,atelier-forest.light,atelier-heath.dark,atelier-heath.light,atelier-lakeside.dark,atelier-lakeside.light,atelier-plateau.dark,atelier-plateau.light,atelier-savanna.dark,atelier-savanna.light,atelier-seaside.dark,atelier-seaside.light,atelier-sulphurpool.dark,atelier-sulphurpool.light,brown_paper,codepen-embed,color-brewer,dark,darkula,default,docco,far,foundation,github-gist,github,googlecode,grayscale,hopscotch,hybrid,idea,ir_black,kimbie.dark,kimbie.light,magula,mono-blue,monokai,monokai_sublime,obsidian,paraiso.dark,paraiso.light,pojoaque,railscasts,rainbow,school_book,solarized_dark,solarized_light,sunburst,tomorrow-night-blue,tomorrow-night-bright,tomorrow-night-eighties,tomorrow-night,tomorrow,vs,xcode,zenburn" .split(","); Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("syntaxHighlighter", getSyntaxHighlighter()); map.put("highlighters", highlighters); map.put("averageSalary", "" + (int) getAverageSalary()); map.put("matchLines", "" + (int) getMatchLines()); map.put("maxLineDepth", "" + (int) getMaxLineDepth()); map.put("minifiedLength", "" + (int) getMinifiedLength()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin_settings.ftl"); }, new FreeMarkerEngine()); get("/admin/reports/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "admin_reports.ftl"); }, new FreeMarkerEngine()); post("/admin/settings/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } if (ISCOMMUNITY) { response.redirect("/admin/settings/"); halt(); } String logo = request.queryParams("logo").trim(); String syntaxHighlighter = request.queryParams("syntaxhighligher"); try { double averageSalary = Double.parseDouble(request.queryParams("averagesalary")); data.saveData(Values.AVERAGESALARY, "" + (int) averageSalary); } catch (NumberFormatException ex) { data.saveData(Values.AVERAGESALARY, Values.DEFAULTAVERAGESALARY); } try { double averageSalary = Double.parseDouble(request.queryParams("matchlines")); data.saveData(Values.MATCHLINES, "" + (int) averageSalary); } catch (NumberFormatException ex) { data.saveData(Values.MATCHLINES, Values.DEFAULTMATCHLINES); } try { double averageSalary = Double.parseDouble(request.queryParams("maxlinedepth")); data.saveData(Values.MAXLINEDEPTH, "" + (int) averageSalary); } catch (NumberFormatException ex) { data.saveData(Values.MAXLINEDEPTH, Values.DEFAULTMAXLINEDEPTH); } try { double minifiedlength = Double.parseDouble(request.queryParams("minifiedlength")); data.saveData(Values.MINIFIEDLENGTH, "" + (int) minifiedlength); } catch (NumberFormatException ex) { data.saveData(Values.MINIFIEDLENGTH, Values.DEFAULTMINIFIEDLENGTH); } data.saveData(Values.LOGO, logo); data.saveData(Values.SYNTAXHIGHLIGHTER, syntaxHighlighter); // Redo anything that requires updates at this point scl = Singleton.getSearchcodeLib(data); response.redirect("/admin/settings/"); halt(); return null; }, new FreeMarkerEngine()); post("/admin/bulk/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } String repos = request.queryParams("repos"); String repolines[] = repos.split("\\r?\\n"); for (String line : repolines) { String[] repoparams = line.split(",", -1); if (repoparams.length == 7) { String branch = repoparams[6].trim(); if (branch.equals(Values.EMPTYSTRING)) { branch = "master"; } String scm = repoparams[1].trim().toLowerCase(); if (scm.equals(Values.EMPTYSTRING)) { scm = "git"; } RepoResult rr = repo.getRepoByName(repoparams[0]); if (rr == null) { repo.saveRepo(new RepoResult(-1, repoparams[0], scm, repoparams[2], repoparams[3], repoparams[4], repoparams[5], branch)); } } } response.redirect("/admin/bulk/"); halt(); return null; }, new FreeMarkerEngine()); post("/admin/repo/", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return null; } String[] reponames = request.queryParamsValues("reponame"); String[] reposcms = request.queryParamsValues("reposcm"); String[] repourls = request.queryParamsValues("repourl"); String[] repousername = request.queryParamsValues("repousername"); String[] repopassword = request.queryParamsValues("repopassword"); String[] reposource = request.queryParamsValues("reposource"); String[] repobranch = request.queryParamsValues("repobranch"); for (int i = 0; i < reponames.length; i++) { if (reponames[i].trim().length() != 0) { String branch = repobranch[i].trim(); if (branch.equals(Values.EMPTYSTRING)) { branch = "master"; } repo.saveRepo(new RepoResult(-1, reponames[i], reposcms[i], repourls[i], repousername[i], repopassword[i], reposource[i], branch)); } } response.redirect("/admin/repo/"); halt(); return null; }, new FreeMarkerEngine()); get("/login/", (request, response) -> { if (getAuthenticatedUser(request) != null) { response.redirect("/admin/"); halt(); return null; } Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "login.ftl"); }, new FreeMarkerEngine()); post("/login/", (req, res) -> { if (req.queryParams().contains("password") && req.queryParams("password") .equals(com.searchcode.app.util.Properties.getProperties().getProperty("password"))) { addAuthenticatedUser(req); res.redirect("/admin/"); halt(); } Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "login.ftl"); }, new FreeMarkerEngine()); get("/logout/", (req, res) -> { removeAuthenticatedUser(req); res.redirect("/"); return null; }); get("/admin/delete/", "application/json", (request, response) -> { if (getAuthenticatedUser(request) == null || !request.queryParams().contains("repoName")) { response.redirect("/login/"); halt(); return false; } String repoName = request.queryParams("repoName"); RepoResult rr = repo.getRepoByName(repoName); if (rr != null) { Singleton.getUniqueDeleteRepoQueue().add(rr); } return true; }, new JsonTransformer()); get("/admin/checkversion/", "application/json", (request, response) -> { if (getAuthenticatedUser(request) == null) { response.redirect("/login/"); halt(); return false; } String version; try { version = IOUtils.toString(new URL("https://searchcode.com/product/version/")).replace("\"", Values.EMPTYSTRING); } catch (IOException ex) { return "Unable to determine if running the latest version. Check https://searchcode.com/product/download/ for the latest release."; } if (App.VERSION.equals(version)) { return "Your searchcode server version " + version + " is the latest."; } else { return "Your searchcode server version " + App.VERSION + " instance is out of date. The latest version is " + version + "."; } }, new JsonTransformer()); get("/file/:codeid/:reponame/*", (request, response) -> { Map<String, Object> map = new HashMap<>(); CodeSearcher cs = new CodeSearcher(); Cocomo2 coco = new Cocomo2(); StringBuilder code = new StringBuilder(); String fileName = Values.EMPTYSTRING; if (request.splat().length != 0) { fileName = request.splat()[0]; } CodeResult codeResult = cs.getByRepoFileName(request.params(":reponame"), fileName); if (codeResult == null) { int codeid = Integer.parseInt(request.params(":codeid")); codeResult = cs.getById(codeid); } if (codeResult == null) { response.redirect("/404/"); halt(); } List<String> codeLines = codeResult.code; for (int i = 0; i < codeLines.size(); i++) { code.append("<span id=\"" + (i + 1) + "\"></span>"); code.append(StringEscapeUtils.escapeHtml4(codeLines.get(i))); code.append("\n"); } boolean highlight = true; if (Integer.parseInt(codeResult.codeLines) > 1000) { highlight = false; } RepoResult repoResult = repo.getRepoByName(codeResult.repoName); if (repoResult != null) { map.put("source", repoResult.getSource()); } map.put("fileName", codeResult.fileName); map.put("codePath", codeResult.codePath); map.put("codeLength", codeResult.codeLines); map.put("languageName", codeResult.languageName); map.put("md5Hash", codeResult.md5hash); map.put("repoName", codeResult.repoName); map.put("highlight", highlight); map.put("repoLocation", codeResult.getRepoLocation()); map.put("codeValue", code.toString()); map.put("highligher", getSyntaxHighlighter()); map.put("codeOwner", codeResult.getCodeOwner()); double estimatedEffort = coco.estimateEffort(scl.countFilteredLines(codeResult.getCode())); int estimatedCost = (int) coco.estimateCost(estimatedEffort, getAverageSalary()); if (estimatedCost != 0 && !scl.languageCostIgnore(codeResult.getLanguageName())) { map.put("estimatedCost", estimatedCost); } map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "coderesult.ftl"); }, new FreeMarkerEngine()); /** * Deprecated should not be used * TODO delete this method */ get("/codesearch/view/:codeid", (request, response) -> { Map<String, Object> map = new HashMap<>(); int codeid = Integer.parseInt(request.params(":codeid")); CodeSearcher cs = new CodeSearcher(); Cocomo2 coco = new Cocomo2(); StringBuilder code = new StringBuilder(); // escape all the lines and include deeplink for line number CodeResult codeResult = cs.getById(codeid); if (codeResult == null) { response.redirect("/404/"); halt(); } List<String> codeLines = codeResult.code; for (int i = 0; i < codeLines.size(); i++) { code.append("<span id=\"" + (i + 1) + "\"></span>"); code.append(StringEscapeUtils.escapeHtml4(codeLines.get(i))); code.append("\n"); } boolean highlight = true; if (Integer.parseInt(codeResult.codeLines) > 1000) { highlight = false; } RepoResult repoResult = repo.getRepoByName(codeResult.repoName); if (repoResult != null) { map.put("source", repoResult.getSource()); } map.put("fileName", codeResult.fileName); map.put("codePath", codeResult.codePath); map.put("codeLength", codeResult.codeLines); map.put("languageName", codeResult.languageName); map.put("md5Hash", codeResult.md5hash); map.put("repoName", codeResult.repoName); map.put("highlight", highlight); map.put("repoLocation", codeResult.getRepoLocation()); map.put("codeValue", code.toString()); map.put("highligher", getSyntaxHighlighter()); map.put("codeOwner", codeResult.getCodeOwner()); double estimatedEffort = coco.estimateEffort(scl.countFilteredLines(codeResult.getCode())); int estimatedCost = (int) coco.estimateCost(estimatedEffort, getAverageSalary()); if (estimatedCost != 0 && !scl.languageCostIgnore(codeResult.getLanguageName())) { map.put("estimatedCost", estimatedCost); } map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "coderesult.ftl"); }, new FreeMarkerEngine()); get("/documentation/", (request, response) -> { Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "documentation.ftl"); }, new FreeMarkerEngine()); get("/search_test/", (request, response) -> { Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "search_test.ftl"); }, new FreeMarkerEngine()); get("/404/", (request, response) -> { Map<String, Object> map = new HashMap<>(); map.put("logoImage", getLogo()); map.put("isCommunity", ISCOMMUNITY); return new ModelAndView(map, "404.ftl"); }, new FreeMarkerEngine()); /** * Test that was being used to display blame information */ // get("/test/:reponame/*", (request, response) -> { // User user = injector.getInstance(User.class); // user.Blame(request.params(":reponame"), request.splat()[0]); // return ""; // }, new JsonTransformer()); }
From source file:com.lsq.httpclient.netpay.BasicInfo.java
public static void main(String[] args) throws Exception { // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("F://test/pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA"); // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("F://??/rsa_public_key_2048.pem", "pem", "RSA"); ////from ww w . ja va 2s. co m // final String url = "http://localhost:8080/interfaceWeb/basicInfo"; // final String url = "https://testapp.sicpay.com:11008/interfaceWeb/basicInfo"; //? // final String url = "http://120.31.132.120:8082/interfaceWeb/basicInfo"; // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:\\document\\key\\000158120120\\GHT_ROOT.pem", "pem", "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:\\document\\key\\000000153990021\\000000153990021.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/000000158120121/000000158120121.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/000000152110003.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/test_pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA"); // PublicKey yhPubKey = TestUtil.getPublicKey(); // PrivateKey hzfPriKey = TestUtil.getPrivateKey(); // final String url = "http://epay.gaohuitong.com:8083/interfaceWeb/basicInfo"; // final String url = "http://gpay.gaohuitong.com:8086/interfaceWeb2/basicInfo"; // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:/document/key/549440155510001/GHT_ROOT.pem", "pem", "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/549440155510001/549440155510001.pem", "pem", null, "RSA"); // final String url = "https://portal.sicpay.com:8087/interfaceWeb/basicInfo"; final String url = TestUtil.interface_url + "basicInfo"; final PublicKey yhPubKey = TestUtil.getPublicKey(); final PrivateKey hzfPriKey = TestUtil.getPrivateKey(); int i = 0; // int j = 0; while (i < 1) { i++; try { HttpClient4Util httpClient4Util = new HttpClient4Util(); StringBuilder sBuilder = new StringBuilder(); sBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sBuilder.append("<merchant>"); sBuilder.append("<head>"); sBuilder.append("<version>2.0.0</version>"); // sBuilder.append("<agencyId>549440155510001</agencyId>"); sBuilder.append("<agencyId>" + TestUtil.merchantId + "</agencyId>"); sBuilder.append("<msgType>01</msgType>"); sBuilder.append("<tranCode>100001</tranCode>"); sBuilder.append("<reqMsgId>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + i + i + "</reqMsgId>"); sBuilder.append("<reqDate>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "</reqDate>"); sBuilder.append("</head>"); sBuilder.append("<body>"); sBuilder.append("<handleType>0</handleType>"); sBuilder.append("<merchantName>LIBTEST1</merchantName>"); sBuilder.append("<shortName>UNCLE HENRY(A)</shortName>"); sBuilder.append("<city>344344</city>"); sBuilder.append( "<merchantAddress>UNIT C 15/FHUA CHIAO COMM CTR 678 NATHAN RD MONGKOK KL</merchantAddress>"); sBuilder.append("<servicePhone>13250538964</servicePhone>"); sBuilder.append("<orgCode></orgCode>"); sBuilder.append("<merchantType>01</merchantType>"); sBuilder.append("<category>5399</category>"); sBuilder.append("<corpmanName>?</corpmanName>"); sBuilder.append("<corpmanId>440103198112214218</corpmanId>"); sBuilder.append("<corpmanPhone>13926015921</corpmanPhone>"); sBuilder.append("<corpmanMobile>13926015921</corpmanMobile>"); sBuilder.append("<corpmanEmail>>zhanglibo@sicpay.com</corpmanEmail>"); sBuilder.append("<bankCode>105</bankCode>"); sBuilder.append("<bankName></bankName>"); sBuilder.append("<bankaccountNo>6250502002603958</bankaccountNo>"); sBuilder.append("<bankaccountName>?</bankaccountName>"); sBuilder.append("<autoCus>0</autoCus>"); sBuilder.append("<remark></remark>"); sBuilder.append("<licenseNo>91440184355798892G</licenseNo>"); // sBuilder.append("<taxRegisterNo></taxRegisterNo>"); // sBuilder.append("<subMerchantNo></subMerchantNo>"); // sBuilder.append("<inviteMerNo></inviteMerNo>"); // sBuilder.append("<county></county>"); // sBuilder.append("<appid>wx04df48e919ef7b28</appid>"); // sBuilder.append("<pid>2015062600009243</pid>"); // sBuilder.append("<childEnter>1</childEnter>"); // sBuilder.append("<ghtEnter>0</ghtEnter>"); // sBuilder.append("<addrType>BUSINESS_ADDRESS</addrType>"); // sBuilder.append("<contactType>LEGAL_PERSON</contactType>"); // sBuilder.append("<mcc>200101110640354</mcc>"); // sBuilder.append("<licenseType>NATIONAL_LEGAL_MERGE</licenseType>"); // sBuilder.append("<authPayDir>http://epay.gaohuitong.com/channel/|http://test.pengjv.com/channel/</authPayDir>"); // sBuilder.append("<scribeAppid>wx04df48e919ef7b28</scribeAppid>"); // sBuilder.append("<contactMan></contactMan>"); // sBuilder.append("<telNo>18675857506</telNo>"); // sBuilder.append("<mobilePhone>18675857506</mobilePhone>"); // sBuilder.append("<email>CSC@sicpay.com</email>"); // sBuilder.append("<licenseBeginDate>20150826</licenseBeginDate>"); // sBuilder.append("<licenseEndDate>20991231</licenseEndDate>"); // sBuilder.append("<licenseRange>?????????????</licenseRange>"); sBuilder.append("</body>"); sBuilder.append("</merchant>"); String plainXML = sBuilder.toString(); byte[] plainBytes = plainXML.getBytes("UTF-8"); String keyStr = "4D22R4846VFJ8HH4"; byte[] keyBytes = keyStr.getBytes("UTF-8"); byte[] base64EncryptDataBytes = Base64.encodeBase64( CryptoUtil.AESEncrypt(plainBytes, keyBytes, "AES", "AES/ECB/PKCS5Padding", null)); String encryptData = new String(base64EncryptDataBytes, "UTF-8"); byte[] base64SingDataBytes = Base64 .encodeBase64(CryptoUtil.digitalSign(plainBytes, hzfPriKey, "SHA1WithRSA")); String signData = new String(base64SingDataBytes, "UTF-8"); byte[] base64EncyrptKeyBytes = Base64 .encodeBase64(CryptoUtil.RSAEncrypt(keyBytes, yhPubKey, 2048, 11, "RSA/ECB/PKCS1Padding")); String encrtptKey = new String(base64EncyrptKeyBytes, "UTF-8"); List<NameValuePair> nvps = new LinkedList<NameValuePair>(); nvps.add(new BasicNameValuePair("encryptData", encryptData)); nvps.add(new BasicNameValuePair("encryptKey", encrtptKey)); // nvps.add(new BasicNameValuePair("agencyId", "549440155510001")); nvps.add(new BasicNameValuePair("agencyId", TestUtil.merchantId)); nvps.add(new BasicNameValuePair("signData", signData)); nvps.add(new BasicNameValuePair("tranCode", "100001")); // nvps.add(new BasicNameValuePair("callBack","http://localhost:801/callback/ghtBindCard.do")); // byte[] retBytes = httpClient4Util.doPost("http://localhost:8080/quickInter/channel/commonSyncInter.do", null, nvps, null); byte[] retBytes = httpClient4Util.doPost(url, null, nvps, null); // byte[] retBytes =httpClient4Util.doPost("http://epay.gaohuitong.com:8082/quickInter/channel/commonSyncInter.do", null, nvps, null); // byte[] retBytes = httpClient4Util.doPost("http://192.168.80.113:8080/quickInter/channel/commonSyncInter.do", null, nvps, null); String response = new String(retBytes, "UTF-8"); System.out.println(" ||" + new String(retBytes, "UTF-8") + "||"); TestEncype t = new TestEncype(); System.out.println(": ||" + t.respDecryption(response) + "||"); System.out.println("i" + i); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.jslsolucoes.tagria.doc.generator.DocGenerator.java
public static void main(String[] args) throws IOException { String workspace = args[0];/*w w w . ja v a2 s . c o m*/ Map<String, List<Tag>> groupments = new HashMap<>(); String html = FileUtils.readFileToString( new File(workspace + "/tagria-lib/src/main/resources/META-INF/html.tld"), CHARSET); String ajax = FileUtils.readFileToString( new File(workspace + "/tagria-lib/src/main/resources/META-INF/ajax.tld"), CHARSET); XStream xStream = new XStream(); xStream.processAnnotations(Taglib.class); Taglib taglibForHtml = (Taglib) xStream.fromXML(html); Taglib taglibForAjax = (Taglib) xStream.fromXML(ajax); List<Tag> tags = new ArrayList<Tag>(); tags.addAll(taglibForHtml.getTags()); tags.addAll(taglibForAjax.getTags()); for (Tag tag : tags) { List<Tag> groups = groupments.get(tag.getGroup()); if (groups == null) { groupments.put(tag.getGroup(), new ArrayList<>()); } groupments.get(tag.getGroup()).add(tag); StringBuilder template = new StringBuilder( "<%@include file=\"../app/taglibs.jsp\"%> " + "<html:view title=\"{title}\"> " + " <html:panel> " + " <html:panelHead label=\"" + tag.getName() + "\"></html:panelHead> " + " <html:panelBody> " + " <html:tabPanel> " + " <html:tab label=\"{about}\" active=\"true\"> " + " <html:alert state=\"warning\"> " + " " + tag.getDescription() + " " + " </html:alert> " + " </html:tab> " + " <html:tab label=\"{attributes}\"> "); if (CollectionUtils.isEmpty(tag.getAttributes())) { template.append("<html:alert state=\"info\" label=\"{tag.empty.attributes}\"></html:alert>"); } else { template.append("<html:table><html:tableLine>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.attribute\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.required\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.type\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.description\"/></html:tableColumn>" + "</html:tableLine>"); for (Attribute attribute : tag.getAttributes()) { template.append("<html:tableLine>" + "<html:tableColumn>" + attribute.getName() + "</html:tableColumn>" + "<html:tableColumn>" + (attribute.getRequired() == null ? false : true) + "</html:tableColumn>" + "<html:tableColumn>" + attribute.getType() + "</html:tableColumn>" + "<html:tableColumn>" + attribute.getDescription() + "</html:tableColumn>" + "</html:tableLine>"); } template.append("</html:table>"); } template.append(" " + " </html:tab> " + " <html:tab label=\"{demo}\"> " + " " + tag.getExample() + " " + " </html:tab> " + " <html:tab label=\"{source}\"> " + " <html:code> " + " <html:view>" + tag.getExampleEscaped() + "</html:view> " + " </html:code> " + " </html:tab> " + " </html:tabPanel> " + " </html:panelBody> " + " </html:panel> " + " </html:view> "); FileUtils.writeStringToFile(new File( workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/component/" + tag.getName() + ".jsp"), template.toString(), CHARSET); } for (List<Tag> values : groupments.values()) { Collections.sort(values, new Comparator<Tag>() { @Override public int compare(Tag o1, Tag o2) { return o1.getName().compareTo(o2.getName()); } }); } StringBuilder menu = new StringBuilder("<html:div cssClass=\"menu\"><html:listGroup>"); for (String key : new TreeSet<String>(groupments.keySet())) { menu.append("<html:listGroupItem><html:collapsable label=\"" + key + "\"><html:listGroup>"); for (Tag tag : groupments.get(key)) { menu.append("<html:listGroupItem><html:link label=\"" + StringUtils.capitalize(tag.getName()) + "\" target=\"conteudo\" url=\"/component/" + tag.getName() + "\"></html:link></html:listGroupItem>"); } menu.append("</html:listGroup></html:collapsable></html:listGroupItem>"); } menu.append("</html:listGroup></html:div>"); File home = new File(workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/app/index.jsp"); FileUtils.writeStringToFile(home, FileUtils.readFileToString(home, CHARSET) .replaceAll("<html:div cssClass=\"menu\">[\\s\\S]*?</html:div>", menu.toString()), CHARSET); }
From source file:hyperheuristics.main.comparisons.ComputeIndicators.java
public static void main(String[] args) throws IOException, InterruptedException { int[] numberOfObjectivesArray = new int[] { 2, 4 }; String[] problems = new String[] { "OO_MyBatis", "OA_AJHsqldb", "OA_AJHotDraw", "OO_BCEL", "OO_JHotDraw", "OA_HealthWatcher", // "OA_TollSystems", "OO_JBoss" }; String[] heuristicFunctions = new String[] { LowLevelHeuristic.CHOICE_FUNCTION, LowLevelHeuristic.MULTI_ARMED_BANDIT, LowLevelHeuristic.RANDOM }; String[] algorithms = new String[] { "NSGA-II", // "SPEA2" };/* w w w . j a v a2s. co m*/ MetricsUtil metricsUtil = new MetricsUtil(); DecimalFormat decimalFormatter = new DecimalFormat("0.00E0"); Mean mean = new Mean(); StandardDeviation standardDeviation = new StandardDeviation(); InvertedGenerationalDistance igd = new InvertedGenerationalDistance(); GenerationalDistance gd = new GenerationalDistance(); Spread spread = new Spread(); Coverage coverage = new Coverage(); for (int objectives : numberOfObjectivesArray) { try (FileWriter IGDWriter = new FileWriter("experiment/IGD_" + objectives + ".tex"); FileWriter spreadWriter = new FileWriter("experiment/SPREAD_" + objectives + ".tex"); FileWriter GDWriter = new FileWriter("experiment/GD_" + objectives + ".tex"); FileWriter coverageWriter = new FileWriter("experiment/COVERAGE_" + objectives + ".tex")) { StringBuilder latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\\documentclass{paper}\n").append("\n") .append("\\usepackage[T1]{fontenc}\n").append("\\usepackage[latin1]{inputenc}\n") .append("\\usepackage[hidelinks]{hyperref}\n").append("\\usepackage{tabulary}\n") .append("\\usepackage{booktabs}\n").append("\\usepackage{multirow}\n") .append("\\usepackage{amsmath}\n").append("\\usepackage{mathtools}\n") .append("\\usepackage{graphicx}\n").append("\\usepackage{array}\n") .append("\\usepackage[linesnumbered,ruled,inoutnumbered]{algorithm2e}\n") .append("\\usepackage{subfigure}\n").append("\\usepackage[hypcap]{caption}\n") .append("\\usepackage{pdflscape}\n").append("\n").append("\\begin{document}\n").append("\n") .append("\\begin{landscape}\n").append("\n"); pfKnown: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR found for $PF_{known}$ for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, Double> igdMap = new HashMap<>(); HashMap<String, Double> gdMap = new HashMap<>(); HashMap<String, Double> spreadMap = new HashMap<>(); HashMap<String, Double> coverageMap = new HashMap<>(); for (String algorithm : algorithms) { double[][] mecbaFront = metricsUtil .readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); igdMap.put(algorithm, igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives)); gdMap.put(algorithm, gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm, spread.spread(mecbaFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm, coverage.coverage(mecbaFront, trueFrontMatrix)); for (String heuristic : heuristicFunctions) { double[][] heuristicFront = metricsUtil.readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/FUN.txt"); igdMap.put(algorithm + "-" + heuristic, igd .invertedGenerationalDistance(heuristicFront, trueFrontMatrix, objectives)); gdMap.put(algorithm + "-" + heuristic, gd.generationalDistance(heuristicFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm + "-" + heuristic, spread.spread(heuristicFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm + "-" + heuristic, coverage.coverage(heuristicFront, trueFrontMatrix)); } } latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTableBuilder = new StringBuilder(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicIGD = igdMap.get(heuristic); double heuristicGD = gdMap.get(heuristic); double heuristicSpread = spreadMap.get(heuristic); double heuristicCoverage = coverageMap.get(heuristic); if (heuristicIGD < bestMeanIGD) { bestMeanIGD = heuristicIGD; bestHeuristicIGD = heuristic; } if (heuristicGD < bestMeanGD) { bestMeanGD = heuristicGD; bestHeuristicGD = heuristic; } if (heuristicSpread > bestMeanSpread) { bestMeanSpread = heuristicSpread; bestHeuristicSpread = heuristic; } if (heuristicCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || igdMap.get(heuristic).equals(igdMap.get(bestHeuristicIGD)); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(igdMap.get(heuristic))); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || gdMap.get(heuristic).equals(gdMap.get(bestHeuristicGD)); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(gdMap.get(heuristic))); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || spreadMap.get(heuristic).equals(spreadMap.get(bestHeuristicSpread)); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(spreadMap.get(heuristic))); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || coverageMap.get(heuristic).equals(coverageMap.get(bestHeuristicCoverage)); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder.append(decimalFormatter.format(coverageMap.get(heuristic))); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } averages: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR averages found for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, double[]> igdMap = new HashMap<>(); HashMap<String, double[]> gdMap = new HashMap<>(); HashMap<String, double[]> spreadMap = new HashMap<>(); HashMap<String, double[]> coverageMap = new HashMap<>(); mocaito: { for (String algorithm : algorithms) { double[] mecbaIGDs = new double[EXECUTIONS]; double[] mecbaGDs = new double[EXECUTIONS]; double[] mecbaSpreads = new double[EXECUTIONS]; double[] mecbaCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] mecbaFront = metricsUtil.readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem + "-" + i + ".NaoDominadas"); mecbaIGDs[i] = igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaGDs[i] = gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaSpreads[i] = spread.spread(mecbaFront, trueFrontMatrix, objectives); mecbaCoverages[i] = coverage.coverage(mecbaFront, trueFrontMatrix); } igdMap.put(algorithm, mecbaIGDs); gdMap.put(algorithm, mecbaGDs); spreadMap.put(algorithm, mecbaSpreads); coverageMap.put(algorithm, mecbaCoverages); } } for (String algorithm : algorithms) { for (String heuristic : heuristicFunctions) { double[] hhIGDs = new double[EXECUTIONS]; double[] hhGDs = new double[EXECUTIONS]; double[] hhSpreads = new double[EXECUTIONS]; double[] hhCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] hhFront = metricsUtil .readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/EXECUTION_" + i + "/FUN.txt"); hhIGDs[i] = igd.invertedGenerationalDistance(hhFront, trueFrontMatrix, objectives); hhGDs[i] = gd.generationalDistance(hhFront, trueFrontMatrix, objectives); hhSpreads[i] = spread.spread(hhFront, trueFrontMatrix, objectives); hhCoverages[i] = coverage.coverage(hhFront, trueFrontMatrix); } igdMap.put(algorithm + "-" + heuristic, hhIGDs); gdMap.put(algorithm + "-" + heuristic, hhGDs); spreadMap.put(algorithm + "-" + heuristic, hhSpreads); coverageMap.put(algorithm + "-" + heuristic, hhCoverages); } } HashMap<String, HashMap<String, Boolean>> igdResult = KruskalWallisTest.test(igdMap); HashMap<String, HashMap<String, Boolean>> gdResult = KruskalWallisTest.test(gdMap); HashMap<String, HashMap<String, Boolean>> spreadResult = KruskalWallisTest.test(spreadMap); HashMap<String, HashMap<String, Boolean>> coverageResult = KruskalWallisTest .test(coverageMap); latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); latexTableBuilder = new StringBuilder(); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicMeanIGD = mean.evaluate(igdMap.get(heuristic)); double heuristicMeanGD = mean.evaluate(gdMap.get(heuristic)); double heuristicMeanSpread = mean.evaluate(spreadMap.get(heuristic)); double heuristicMeanCoverage = mean.evaluate(coverageMap.get(heuristic)); if (heuristicMeanIGD < bestMeanIGD) { bestMeanIGD = heuristicMeanIGD; bestHeuristicIGD = heuristic; } if (heuristicMeanGD < bestMeanGD) { bestMeanGD = heuristicMeanGD; bestHeuristicGD = heuristic; } if (heuristicMeanSpread > bestMeanSpread) { bestMeanSpread = heuristicMeanSpread; bestHeuristicSpread = heuristic; } if (heuristicMeanCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicMeanCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || !igdResult.get(heuristic).get(bestHeuristicIGD); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(mean.evaluate(igdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(igdMap.get(heuristic))) + ")"); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || !gdResult.get(heuristic).get(bestHeuristicGD); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(mean.evaluate(gdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(gdMap.get(heuristic))) + ")"); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || !spreadResult.get(heuristic).get(bestHeuristicSpread); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(mean.evaluate(spreadMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(spreadMap.get(heuristic))) + ")"); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || !coverageResult.get(heuristic).get(bestHeuristicCoverage); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder .append(decimalFormatter.format(mean.evaluate(coverageMap.get(heuristic)))) .append(" (") .append(decimalFormatter .format(standardDeviation.evaluate(coverageMap.get(heuristic)))) .append(")"); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } latexTableBuilder.append("\\end{landscape}\n\n").append("\\end{document}"); String latexTable = latexTableBuilder.toString(); IGDWriter.write(latexTable); spreadWriter.write(latexTable); GDWriter.write(latexTable); coverageWriter.write(latexTable); } } }
From source file:AdminExample.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account. String user1Email = ""; //You need access to these two email account. String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. //joe@gmail.com will get email sent to joe+user1@gmail.com try {//from www.j a v a 2s . c o m BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Adding user " + user1Email); //Add the users: User user = new User(); user.setEmail(user1Email); user.setAdmin(false); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser1Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId()); user = new User(); user.setEmail(user2Email); user.setAdmin(true); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser2Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId()); System.out.println("Please visit the email inbox for the users " + user1Email + " and " + user2Email + " and confirm membership to the account."); System.out.print("Press Enter to continue"); in.readLine(); //List all the users of the org connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() { }); System.out.println("The following are members of your account: "); for (User orgUser : users) { System.out.println("\t" + orgUser.getEmail()); } //Create a sheet as the admin Sheet newSheet = new Sheet(); newSheet.setName("Admin's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user1 newSheet = new Sheet(); newSheet.setName("User 1's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); //Here is where the magic happens - Any action performed in this call will be on behalf of the //user provided. Note that this person must be a confirmed member of your org. //Also note that the email address is url-encoded. connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user2 newSheet = new Sheet(); newSheet.setName("User 2's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //List all the sheets in the org: System.out.println("The following sheets are owned by members of your account: "); connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() { }); for (Sheet orgSheet : allSheets) { System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner()); } //Now delete user1 and transfer their sheets to user2 connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "") + "?transferTo=" + newUser2Result.getResult().getId()).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("DELETE"); Result<Object> resultObject = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Object>>() { }); System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred()); } catch (IOException e) { InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:Main.java
public static String[] getlines(StringBuilder text) { String[] lines = text.toString().split("\\n"); return lines; }
From source file:Main.java
public static String getDurationStr(long duration) { StringBuilder sb = new StringBuilder(); return sb.toString(); }
From source file:Main.java
public static String getUserAgent(Context context) { StringBuilder sb = new StringBuilder("MAC_XM"); return sb.toString(); }
From source file:Main.java
public static String charAtStr(StringBuilder stringBuilder) { String str = stringBuilder.toString(); String s = str.substring(0, str.length() - 1); return s;/*from www . j a v a 2s . c om*/ }