List of usage examples for java.net URL getPath
public String getPath()
From source file:org.openmrs.module.referenceapplication.page.controller.LoginPageController.java
private String getRedirectUrlFromReferer(PageRequest pageRequest) { String referer = pageRequest.getRequest().getHeader("Referer"); String redirectUrl = ""; if (referer != null) { if (referer.contains("http://") || referer.contains("https://")) { try { URL refererUrl = new URL(referer); String refererPath = refererUrl.getPath(); String refererContextPath = refererPath.substring(0, refererPath.indexOf('/', 1)); if (StringUtils.equals(pageRequest.getRequest().getContextPath(), refererContextPath)) { redirectUrl = refererPath; }// w ww . j a v a 2s . co m } catch (MalformedURLException e) { log.error(e.getMessage()); } } else { redirectUrl = pageRequest.getRequest().getHeader("Referer"); } } return StringEscapeUtils.escapeHtml(redirectUrl); }
From source file:biz.neustar.nexus.plugins.gitlab.GitlabAuthenticatingRealmIT.java
License:asdf
@Test public void testPlugin() throws Exception { assertTrue(nexus().isRunning());//from w w w . j a v a 2s. c o m URL nexusUrl = nexus().getUrl(); URI uri = new URIBuilder().setHost(nexusUrl.getHost()).setPath(nexusUrl.getPath()) .setPort(nexusUrl.getPort()).setParameters(URLEncodedUtils.parse(nexusUrl.getQuery(), UTF_8)) .setScheme(nexusUrl.getProtocol()).setUserInfo("jdamick", "asdfasdfasdf").build() .resolve("content/groups/public/"); HttpClient httpclient = HttpClientBuilder.create().build(); {// request 1 HttpGet req1 = new HttpGet(uri); HttpResponse resp1 = httpclient.execute(req1); assertEquals(200, resp1.getStatusLine().getStatusCode()); RecordedRequest request = server.takeRequest(); // 1 request recorded assertEquals("/api/v3/session", request.getPath()); req1.releaseConnection(); } // failure checks { // request 2 HttpGet req2 = new HttpGet(uri); HttpResponse resp2 = httpclient.execute(req2); assertEquals(401, resp2.getStatusLine().getStatusCode()); req2.releaseConnection(); } { // request 3 HttpGet req3 = new HttpGet(uri); HttpResponse resp3 = httpclient.execute(req3); assertEquals(401, resp3.getStatusLine().getStatusCode()); req3.releaseConnection(); } }
From source file:com.thoughtworks.go.config.GoConfigMigration.java
private String upgrade(String originalContent, URL upgradeScript) { try (InputStream xslt = upgradeScript.openStream()) { ByteArrayOutputStream convertedConfig = new ByteArrayOutputStream(); transformer(upgradeScript.getPath(), xslt).transform( new StreamSource(new ByteArrayInputStream(originalContent.getBytes())), new StreamResult(convertedConfig)); return convertedConfig.toString(); } catch (TransformerException e) { throw bomb("Couldn't transform configuration file using upgrade script " + upgradeScript.getPath(), e); } catch (IOException e) { throw bomb("Couldn't write converted config file", e); }/*from www . j a va2 s . com*/ }
From source file:name.martingeisse.webide.nodejs.AbstractNodejsServer.java
/** * Starts this server.//from w ww . j av a2 s . c o m */ public void start() { // determine the path of the associated script URL url = getScriptUrl(); if (!url.getProtocol().equals("file")) { throw new RuntimeException("unsupported protocol for associated script URL: " + url); } File scriptFile = new File(url.getPath()); // build the command line CommandLine commandLine = new CommandLine(Configuration.getBashPath()); commandLine.addArgument("--login"); commandLine.addArgument("-c"); commandLine.addArgument("node " + scriptFile.getName(), false); // build I/O streams ByteArrayInputStream inputStream = null; OutputStream outputStream = System.err; OutputStream errorStream = System.err; ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream); // build an environment map that contains the path to the node_modules Map<String, String> environment = new HashMap<String, String>(); environment.put("NODE_PATH", new File("lib/node_modules").getAbsolutePath()); // run Node.js Executor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setStreamHandler(streamHandler); try { executor.setWorkingDirectory(scriptFile.getParentFile()); executor.execute(commandLine, environment, new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { } @Override public void onProcessComplete(int exitValue) { } }); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java
/** * Scan a classloader for classes under the given package. * @param pkg package name/* w w w . j a v a2 s . com*/ * @param loader classloader * @param lookInsideJars whether to consider classes inside jars or only "unpacked" class files * @return matching class names (will not attemp to actually load these classes) */ private Collection<String> scanClasspath(String pkg, ClassLoader loader, boolean lookInsideJars) { Collection<String> classes = Lists.newArrayList(); Enumeration<URL> resources; String packageDir = pkg.replace(PACKAGE_SEPARATOR, JAR_PATH_SEPARATOR) + JAR_PATH_SEPARATOR; try { resources = loader.getResources(packageDir); } catch (IOException e) { s_log.warn("couldn't scan package", e); return classes; } while (resources.hasMoreElements()) { URL resource = resources.nextElement(); String path = resource.getPath(); s_log.debug("processing path {}", path); if (path.startsWith(FILE_URL_PREFIX)) { if (lookInsideJars) { String jarFilePath = StringUtils.substringBetween(path, FILE_URL_PREFIX, NESTED_FILE_URL_SEPARATOR); try { JarFile jarFile = new JarFile(jarFilePath); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { String entryName = entries.nextElement().getName(); if (entryName.startsWith(packageDir) && entryName.endsWith(CLASS_NAME_SUFFIX)) { String potentialClassName = entryName.substring(packageDir.length(), entryName.length() - CLASS_NAME_SUFFIX.length()); if (!potentialClassName.contains(JAR_PATH_SEPARATOR)) { classes.add(pkg + PACKAGE_SEPARATOR + potentialClassName); } } } } catch (IOException e) { s_log.warn("couldn't open jar file", e); } } } else { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { String[] files = dir.list(); for (String file : files) { s_log.debug("file {}", file); if (file.endsWith(CLASS_NAME_SUFFIX)) { classes.add(pkg + PACKAGE_SEPARATOR + StringUtils.removeEnd(file, CLASS_NAME_SUFFIX)); } } } } } return classes; }
From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java
/** * The main method which upgrade database */*from w ww . j a v a 2 s . com*/ * @throws JAXBException * @throws FileNotFoundException */ private void startUpgrade() throws JAXBException, FileNotFoundException { DataSource source = dataSource.database(); String schema = OpenFlameConfig.DB_SCHEMA.getValue(); if (source == null || !DBUtils.dbExists(source, schema)) return; dataSource.refreshDBProperties(); logger.info("Start upgrade"); Version databaseVersion = getDatabaseVersion(OpenFlame.PACKAGE); logger.info("Database version for '" + OpenFlame.PACKAGE + "' is: " + databaseVersion); Pattern pattern = Pattern.compile(SchemaUpgrader.UPGRADE_SCRIPT_PATTERN); URL scriptFolderPath = getClass().getResource(upgradeFolderPath); File updateScriptsFolder = new File(scriptFolderPath.getPath()); if (updateScriptsFolder.isDirectory() && updateScriptsFolder.exists()) { FileFilter fileFilter = new RegexFileFilter(UPGRADE_SCRIPT_PATTERN); File[] scripts = updateScriptsFolder.listFiles(fileFilter); scripts = SortFileUtils.sortingByName(scripts, false); for (File script : scripts) { String scriptName = script.getName(); String scriptPath = script.getAbsolutePath(); Matcher m = pattern.matcher(scriptName); if (m.find()) { String fromVersionStr = m.group(1); String toVersionStr = m.group(2); Integer fromVersion = VersionUtils.convertToNumber(fromVersionStr); Integer toVersion = VersionUtils.convertToNumber(toVersionStr); Version ver = new Version(fromVersion, toVersion, scriptPath); if (ver.compareTo(databaseVersion) == 0) { upgradeExecutor.upgrade(ver, OpenFlame.PACKAGE); databaseVersion = updateDatabaseVersion(OpenFlame.PACKAGE, ver); } } } } else { logger.warn("Script folder has not been found by path:[" + upgradeFolderPath + "]"); } logger.info("Finish upgrade"); }
From source file:com.gatf.executor.report.ReportHandler.java
public static void doTAReporting(String prefix, AcceptanceTestContext acontext, boolean isLoadTestingEnabled, TestExecutionPercentile testPercentiles, TestExecutionPercentile runPercentiles) { Map<String, List<Long>> testPercentileValues = testPercentiles.getPercentileTimes(); Map<String, List<Long>> runPercentileValues = runPercentiles.getPercentileTimes(); GatfExecutorConfig config = acontext.getGatfExecutorConfig(); VelocityContext context = new VelocityContext(); try {/*ww w . j a v a 2 s . co m*/ String reportingJson = new ObjectMapper().writeValueAsString(testPercentileValues); context.put("testcaseTAReports", reportingJson); if (testPercentileValues.size() > 0) context.put("isShowTAWrapper", testPercentileValues.values().iterator().next().size() > 0); else context.put("isShowTAWrapper", false); if (runPercentileValues.size() > 0) { List<Long> times90 = new ArrayList<Long>(); List<Long> times50 = new ArrayList<Long>(); for (List<Long> times : runPercentileValues.values()) { times90.add(times.get(0)); times50.add(times.get(1)); } runPercentileValues.put("All", times90); Collections.sort(times90); int index = Math.round((float) 0.9 * times90.size()); long time = times90.get(index - 1); times90.clear(); times90.add(time); Collections.sort(times50); index = Math.round((float) 0.5 * times50.size()); time = times50.get(index - 1); times90.add(time); } reportingJson = new ObjectMapper().writeValueAsString(runPercentileValues); context.put("runTAReports", reportingJson); } catch (Exception e) { e.printStackTrace(); } try { InputStream resourcesIS = GatfTestCaseExecutorMojo.class.getResourceAsStream("/gatf-resources.zip"); if (resourcesIS != null) { File basePath = null; if (config.getOutFilesBasePath() != null) basePath = new File(config.getOutFilesBasePath()); else { URL url = Thread.currentThread().getContextClassLoader().getResource("."); basePath = new File(url.getPath()); } File resource = new File(basePath, config.getOutFilesDir()); VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); context.put("isLoadTestingEnabled", isLoadTestingEnabled); StringWriter writer = new StringWriter(); engine.mergeTemplate("/gatf-templates/index-ta.vm", context, writer); prefix = prefix == null ? "" : prefix; BufferedWriter fwriter = new BufferedWriter(new FileWriter(new File( resource.getAbsolutePath() + SystemUtils.FILE_SEPARATOR + prefix + "index-ta.html"))); fwriter.write(writer.toString()); fwriter.close(); /*if(distributedTestStatus!=null && distributedTestStatus.getReportFileContent().size()<5) { distributedTestStatus.getReportFileContent().put("", writer.toString()); }*/ } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ikanow.infinit.e.harvest.extraction.document.file.InfiniteFile.java
public URI getURI() throws MalformedURLException, URISyntaxException { // (note this doesn't work nicely with spaces) if (null != _smbFile) { URL url = _smbFile.getURL(); return new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); // (this odd construct is needed to handle spaces in paths) } else {/*w w w . j a v a 2 s.c o m*/ return _localFile.toURI(); // (confirmed spaces in paths works here) } }
From source file:com.streamreduce.core.service.SearchServiceImpl.java
@Override public List<SobaMessage> searchMessages(Account account, String resourceName, Map<String, String> searchParameters, JSONObject query) { if (!enabled) { return Collections.emptyList(); }/*from ww w. j av a 2 s .c om*/ URL searchBaseUrl = createBaseURLForSearchIndexAndType(account); String path = searchBaseUrl.getPath() + resourceName; JSONObject response = makeRequest(path, query, searchParameters, "GET"); if (response.containsKey("_source")) { SobaMessage sobaMessage = createSobaMessageFromJson(response.getJSONObject("_source")); return Lists.newArrayList(sobaMessage); } else { JSONArray hits = response.getJSONObject("hits").getJSONArray("hits"); List<SobaMessage> sobaMessages = new ArrayList<>(); for (Object hit : hits) { JSONObject hitAsJson = (JSONObject) hit; JSONObject sobaMessageAsJson = hitAsJson.getJSONObject("_source"); sobaMessages.add(createSobaMessageFromJson(sobaMessageAsJson)); } return sobaMessages; } }
From source file:com.esri.gpt.control.webharvest.extensions.localfolder.LocalFolderDataProcessor.java
@Override public void onStart(ExecutionUnit unit) { try {/*from w w w . j a v a 2 s . co m*/ URL hostUrl = new URL(unit.getRepository().getHostUrl()); destinationFolder = rootFolder != null ? new File(rootFolder, hostUrl.getHost()) : null; subFolder = splitPath(hostUrl.getPath()); } catch (MalformedURLException ex) { LOG.log(Level.SEVERE, "Error starting harvesting", ex); } }