List of usage examples for java.net URI getPath
public String getPath()
From source file:fedora.server.utilities.ServerUtility.java
/** * Tell whether the given URL appears to be referring to somewhere within * the Fedora webapp.//from w w w. j av a 2s. com */ public static boolean isURLFedoraServer(String url) { // scheme must be http or https URI uri = URI.create(url); String scheme = uri.getScheme(); if (!scheme.equals("http") && !scheme.equals("https")) { return false; } // host must be configured hostname or localhost String fHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue(); String host = uri.getHost(); if (!host.equals(fHost) && !host.equals("localhost")) { return false; } // path must begin with configured webapp context String path = uri.getPath(); String fedoraContext = CONFIG.getParameter(FEDORA_SERVER_CONTEXT).getValue(); if (!path.startsWith("/" + fedoraContext + "/")) { return false; } // port specification must match http or https port as appropriate String httpPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue(); String httpsPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue(); if (uri.getPort() == -1) { // unspecified, so fedoraPort must be 80 (http), or 443 (https) if (scheme.equals("http")) { return httpPort.equals("80"); } else { return httpsPort.equals("443"); } } else { // specified, so must match appropriate http or https port String port = "" + uri.getPort(); if (scheme.equals("http")) { return port.equals(httpPort); } else { return port.equals(httpsPort); } } }
From source file:org.apache.jena.jdbc.remote.RemoteEndpointDriver.java
/** * Strips the last component of the given URI if possible * //from w w w . j av a2 s.c o m * @param input * URI * @return Reduced URI or null if no further reduction is possible */ private static String stripLastComponent(String input) { try { URI uri = new URI(input); if (uri.getFragment() != null) { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), null).toString(); } else if (uri.getQuery() != null) { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null).toString(); } else if (uri.getPath() != null) { // Try and strip off last segment of the path String currPath = uri.getPath(); if (currPath.endsWith("/")) { currPath = currPath.substring(0, currPath.length() - 1); if (currPath.length() == 0) currPath = null; return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), currPath, null, null).toString(); } else if (currPath.contains("/")) { currPath = currPath.substring(0, currPath.lastIndexOf('/') + 1); if (currPath.length() == 0) currPath = null; return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), currPath, null, null).toString(); } else { // If path is non-null it must always contain a / // otherwise it would be an invalid path // In this case there are no further components to strip return null; } } else { // No further components to strip return null; } } catch (URISyntaxException e) { // Error stripping component return null; } }
From source file:com.t3.macro.api.views.MacroButtonView.java
public static Object executeLink(String link) throws MacroException { try {// ww w. java 2s . com URI u = new URI(link); MacroButtonProperties mbp; Token t = null; //campaign macro if ("CampaignPanel".equals(u.getHost())) { CampaignFunctions cf = new CampaignFunctions(); MacroButtonView mv = cf.getCampaignMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1)); if (mv == null) throw new IllegalArgumentException( "Campaign macro '" + URLDecoder.decode(u.getPath(), "utf8") + " not found."); else mbp = mv.macro; } //global macro else if ("GlobalPanel".equals(u.getHost())) { CampaignFunctions cf = new CampaignFunctions(); MacroButtonView mv = cf.getGlobalMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1)); if (mv == null) throw new IllegalArgumentException( "Global macro '" + URLDecoder.decode(u.getPath(), "utf8").substring(1) + " not found."); else mbp = mv.macro; } //token macro else { t = TabletopTool.getFrame().findToken(new GUID(u.getHost())); mbp = t.getMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1), false); } HashMap<String, Object> arguments = new HashMap<String, Object>(); if (u.getQuery() != null) { for (String a : StringUtils.split(u.getQuery(), '&')) { String[] aps = StringUtils.split(a, '='); arguments.put(aps[0], URLDecoder.decode(aps[1], "utf8")); } } return mbp.executeMacro(t, arguments); } catch (UnsupportedEncodingException | URISyntaxException e) { throw new MacroException(e); } }
From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java
public static SeleniumHttpProxy create(int id, SeleniumResourceImpl resource, String prefix, long timeout, long maxIdleTime, String accessUrl, ScheduledExecutorService healthCheckExecutor) { URI oUri = URI.create(resource.getOriginalUrl()); SeleniumHttpProxy proxy = new SeleniumHttpProxy(oUri.getScheme(), prefix, oUri.getHost(), oUri.getPort(), oUri.getPath()); proxy.id = id;/*from w w w. jav a2 s . c o m*/ proxy.resource = resource; proxy.timeout = timeout; proxy.accessUrl = accessUrl; proxy.maxIdleTime = maxIdleTime; proxy.healthCheckClient = createHealthCheckHttpClient(); proxy.healthCheckExecutor = healthCheckExecutor; // set resource to DISCONNECTED first resource.setState(ResourceState.DISCONNECTED); proxy.nextHealthCheck = healthCheckExecutor.schedule(proxy.checkStatusRunnable, 2000, TimeUnit.MILLISECONDS); return proxy; }
From source file:com.sap.prd.mobile.ios.mios.SCMUtil.java
public static String getConnectionString(final Properties versionInfo, final boolean hideConfidentialInformation) throws IOException { final String type = versionInfo.getProperty("type"); final StringBuilder connectionString = new StringBuilder(128); if (type != null && type.equals("git")) { final String repo = versionInfo.getProperty("repo"); if (StringUtils.isBlank(repo)) { if (!StringUtils.isBlank(versionInfo.getProperty("repo_1"))) { throw new IllegalStateException( "Multipe git repositories provided. This use case is not supported. Provide only one git repository."); }/*from w ww. j a v a2s . c o m*/ throw new IllegalStateException("No git repository provided. "); } if (hideConfidentialInformation) { try { URI uri = new URI(repo); int port = uri.getPort(); if (port == -1) { final String scheme = uri.getScheme(); if (scheme != null && gitDefaultPorts.containsKey(scheme)) { port = gitDefaultPorts.get(scheme); } } connectionString.append(port); if (uri.getHost() != null) { connectionString.append(uri.getPath()); } } catch (URISyntaxException e) { throw new IllegalStateException(String.format("Invalid repository uri: %s", repo)); } } else { connectionString.append(PROTOCOL_PREFIX_GIT).append(repo); } } else { final String port = versionInfo.getProperty("port"); if (StringUtils.isBlank(port)) throw new IllegalStateException("No SCM port provided."); final String depotPath = versionInfo.getProperty("depotpath"); if (hideConfidentialInformation) { try { URI perforceUri = new URI("perforce://" + port); int _port = perforceUri.getPort(); if (_port == -1) { _port = PERFORCE_DEFAULT_PORT; } connectionString.append(_port); connectionString.append(depotPath); } catch (URISyntaxException e) { throw new IllegalStateException(String.format("Invalid port: %s", port)); } } else { if (StringUtils.isBlank(depotPath)) throw new IllegalStateException("No depot path provided."); connectionString.append(PROTOCOL_PREFIX_PERFORCE).append(port).append(":") .append(getDepotPath(depotPath)); } } return connectionString.toString(); }
From source file:co.cask.cdap.metrics.query.MetricQueryParser.java
static MetricDeleteQuery parseDelete(URI requestURI, String metricPrefix) throws MetricsPathException { MetricDataQueryBuilder builder = new MetricDataQueryBuilder(); parseContext(requestURI.getPath(), builder); builder.setStartTs(0);/*w w w .j ava 2 s . co m*/ builder.setEndTs(Integer.MAX_VALUE - 1); builder.setMetricName(metricPrefix); MetricDataQuery query = builder.build(); return new MetricDeleteQuery(query.getStartTs(), query.getEndTs(), query.getMetrics().keySet(), query.getSliceByTags()); }
From source file:org.keycloak.helper.TestsHelper.java
public static String getCreatedId(Response response) { URI location = response.getLocation(); if (!response.getStatusInfo().equals(Response.Status.CREATED)) { Response.StatusType statusInfo = response.getStatusInfo(); throw new WebApplicationException("Create method returned status " + statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response); }// ww w . j a v a 2s . c o m if (location == null) { return null; } String path = location.getPath(); return path.substring(path.lastIndexOf('/') + 1); }
From source file:Main.java
/** * Extract the UUID part from a MusicBrainz identifier. * /* www . j a v a 2 s . c o m*/ * This function takes a MusicBrainz ID (an absolute URI) as the input * and returns the UUID part of the URI, thus turning it into a relative * URI. If <code>uriStr</code> is null or a relative URI, then it is * returned unchanged. * * The <code>resType</code> parameter can be used for error checking. * Set it to 'artist', 'release', or 'track' to make sure * <code>uriStr</code> is a syntactically valid MusicBrainz identifier * of the given resource type. If it isn't, an * <code>IllegalArgumentException</code> exception is raised. This error * checking only works if <code>uriStr</code> is an absolute URI, of course. * * Example: * >>> MBUtils.extractUuid('http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5', 'artist') * 'c0b2500e-0cef-4130-869d-732b23ed9df5' * * @param uriStr A string containing a MusicBrainz ID (an URI), or null * @param resType A string containing a resource type * @return A String containing a relative URI or null * @throws URISyntaxException */ public static String extractUuid(String uriStr, String resType) { if (uriStr == null) { return null; } URI uri; try { uri = new URI(uriStr); } catch (URISyntaxException e) { return uriStr; // not really a valid URI, probably the UUID } if (uri.getScheme() == null) { return uriStr; // not really a valid URI, probably the UUID } if (!"http".equals(uri.getScheme()) || !"musicbrainz.org".equals(uri.getHost())) { throw new IllegalArgumentException(uri.toString() + " is no MB ID"); } String regex = "^/(label|artist|release-group|release|recording|work|collection)/([^/]*)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(uri.getPath()); if (m.matches()) { if (resType == null) { return m.group(2); } else { if (resType.equals(m.group(1))) { return m.group(2); } else { throw new IllegalArgumentException("expected '" + resType + "' Id"); } } } else { throw new IllegalArgumentException("'" + uriStr + " is no valid MB id"); } }
From source file:it.unimi.di.big.mg4j.index.Index.java
/** Returns a new index using the given URI. * //from w ww. j a v a 2s . c o m * @param ioFactory the factory that will be used to perform I/O, or <code>null</code> (implying the {@link IOFactory#FILESYSTEM_FACTORY} for disk-based indices). * @param uri the URI defining the index. * @param randomAccess whether the index should be accessible randomly. * @param documentSizes if true, document sizes will be loaded (note that sometimes document sizes * might be loaded anyway because the compression method for positions requires it). * @param maps if true, {@linkplain StringMap term} and {@linkplain PrefixMap prefix} maps will be guessed and loaded (this * feature might not be available with some kind of index). */ public static Index getInstance(IOFactory ioFactory, final CharSequence uri, final boolean randomAccess, final boolean documentSizes, final boolean maps) throws IOException, ConfigurationException, URISyntaxException, ClassNotFoundException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { /* If the scheme is mg4j, then we are creating a remote * index. If it is null, we assume it is a property file and load it. Otherwise, we * assume it is a valid property file URI and try to download it. */ final String uriString = uri.toString(); /*if ( uriString.startsWith( "mg4j:" ) ) { if ( ioFactory != null ) throw new IllegalAccessError( "You cannot specify a factory for a remote index" ); final URI u = new URI( uriString ); return IndexServer.getIndex( u.getHost(), u.getPort(), randomAccess, documentSizes ); }*/ final String basename, query; if (ioFactory == null) ioFactory = IOFactory.FILESYSTEM_FACTORY; if (uriString.startsWith("file:")) { final URI u = new URI(uriString); basename = u.getPath(); query = u.getQuery(); } else { final int questionMarkPos = uriString.indexOf('?'); basename = questionMarkPos == -1 ? uriString : uriString.substring(0, questionMarkPos); query = questionMarkPos == -1 ? null : uriString.substring(questionMarkPos + 1); } LOGGER.debug("Searching for an index with basename " + basename + "..."); final Properties properties = IOFactories.loadProperties(ioFactory, basename + DiskBasedIndex.PROPERTIES_EXTENSION); LOGGER.debug("Properties: " + properties); // We parse the key/value pairs appearing in the query part. final EnumMap<UriKeys, String> queryProperties = new EnumMap<UriKeys, String>(UriKeys.class); if (query != null) { String[] keyValue = query.split(";"); for (int i = 0; i < keyValue.length; i++) { String[] piece = keyValue[i].split("="); if (piece.length != 2) throw new IllegalArgumentException("Malformed key/value pair: " + keyValue[i]); // Convert to standard keys boolean found = false; for (UriKeys key : UriKeys.values()) if (found = PropertyBasedDocumentFactory.sameKey(key, piece[0])) { queryProperties.put(key, piece[1]); break; } if (!found) throw new IllegalArgumentException("Unknown key: " + piece[0]); } } // Compatibility with previous versions String className = properties.getString(Index.PropertyKeys.INDEXCLASS, "(missing index class)") .replace(".dsi.", ".di."); Class<?> indexClass = Class.forName(className); // It is a cluster. if (IndexCluster.class.isAssignableFrom(indexClass)) return IndexCluster.getInstance(basename, randomAccess, documentSizes, queryProperties); // It is a disk-based index. return DiskBasedIndex.getInstance(ioFactory, basename, properties, randomAccess, documentSizes, maps, queryProperties); }
From source file:com.ibm.jaggr.core.test.TestUtils.java
public static IAggregator createMockAggregator(Ref<IConfig> configRef, File workingDirectory, List<InitParam> initParams, Class<?> aggregatorProxyClass, IHttpTransport transport) throws Exception { final IAggregator mockAggregator = EasyMock.createNiceMock(IAggregator.class); IOptions options = new OptionsImpl(false, null); options.setOption(IOptions.DELETE_DELAY, "0"); if (initParams == null) { initParams = new LinkedList<InitParam>(); }/*from w w w . j ava 2s . c o m*/ final InitParams aggInitParams = new InitParams(initParams); boolean createConfig = (configRef == null); if (workingDirectory == null) { workingDirectory = new File(System.getProperty("java.io.tmpdir")); } final Ref<ICacheManager> cacheMgrRef = new Ref<ICacheManager>(null); final Ref<IHttpTransport> transportRef = new Ref<IHttpTransport>( transport == null ? new TestDojoHttpTransport() : transport); final Ref<IExecutors> executorsRef = new Ref<IExecutors>(new ExecutorsImpl(new SynchronousExecutor(), null, new SynchronousScheduledExecutor(), new SynchronousScheduledExecutor())); final File workdir = workingDirectory; EasyMock.expect(mockAggregator.getWorkingDirectory()).andReturn(workingDirectory).anyTimes(); EasyMock.expect(mockAggregator.getName()).andReturn("test").anyTimes(); EasyMock.expect(mockAggregator.getOptions()).andReturn(options).anyTimes(); EasyMock.expect(mockAggregator.getExecutors()).andAnswer(new IAnswer<IExecutors>() { public IExecutors answer() throws Throwable { return executorsRef.get(); } }).anyTimes(); if (createConfig) { configRef = new Ref<IConfig>(null); // ConfigImpl constructor calls IAggregator.newResource() EasyMock.expect(mockAggregator.newResource((URI) EasyMock.anyObject())) .andAnswer(new IAnswer<IResource>() { public IResource answer() throws Throwable { return mockAggregatorNewResource((URI) EasyMock.getCurrentArguments()[0], workdir); } }).anyTimes(); } EasyMock.expect(mockAggregator.substituteProps((String) EasyMock.anyObject())) .andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return (String) EasyMock.getCurrentArguments()[0]; } }).anyTimes(); EasyMock.expect(mockAggregator.substituteProps((String) EasyMock.anyObject(), (IAggregator.SubstitutionTransformer) EasyMock.anyObject())).andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return (String) EasyMock.getCurrentArguments()[0]; } }).anyTimes(); EasyMock.expect(mockAggregator.newLayerCache()).andAnswer(new IAnswer<ILayerCache>() { public ILayerCache answer() throws Throwable { return new LayerCacheImpl(mockAggregator); } }).anyTimes(); EasyMock.expect(mockAggregator.newModuleCache()).andAnswer(new IAnswer<IModuleCache>() { public IModuleCache answer() throws Throwable { return new ModuleCacheImpl(); } }).anyTimes(); EasyMock.expect(mockAggregator.newGzipCache()).andAnswer(new IAnswer<IGzipCache>() { public IGzipCache answer() throws Throwable { return new GzipCacheImpl(); } }).anyTimes(); EasyMock.expect(mockAggregator.getInitParams()).andAnswer(new IAnswer<InitParams>() { public InitParams answer() throws Throwable { return aggInitParams; } }).anyTimes(); EasyMock.replay(mockAggregator); IAggregator mockAggregatorProxy = mockAggregator; if (aggregatorProxyClass != null) { mockAggregatorProxy = (IAggregator) aggregatorProxyClass .getConstructor(new Class[] { IAggregator.class }).newInstance(mockAggregator); } TestCacheManager cacheMgr = new TestCacheManager(mockAggregatorProxy, 1); cacheMgrRef.set(cacheMgr); //((IOptionsListener)cacheMgrRef.get()).optionsUpdated(options, 1); if (createConfig) { configRef.set(new ConfigImpl(mockAggregatorProxy, workingDirectory.toURI(), "{}")); } EasyMock.reset(mockAggregator); EasyMock.expect(mockAggregator.getWorkingDirectory()).andReturn(workingDirectory).anyTimes(); EasyMock.expect(mockAggregator.getOptions()).andReturn(options).anyTimes(); EasyMock.expect(mockAggregator.getName()).andReturn("test").anyTimes(); EasyMock.expect(mockAggregator.getTransport()).andAnswer(new IAnswer<IHttpTransport>() { public IHttpTransport answer() throws Throwable { return transportRef.get(); } }).anyTimes(); EasyMock.expect(mockAggregator.newResource((URI) EasyMock.anyObject())).andAnswer(new IAnswer<IResource>() { public IResource answer() throws Throwable { return mockAggregatorNewResource((URI) EasyMock.getCurrentArguments()[0], workdir); } }).anyTimes(); EasyMock.expect(mockAggregator.getResourceFactory(EasyMock.isA(Mutable.class))) .andAnswer(new IAnswer<IResourceFactory>() { public IResourceFactory answer() throws Throwable { Mutable<URI> uriRef = (Mutable<URI>) EasyMock.getCurrentArguments()[0]; URI uri = uriRef.getValue(); if (!uri.isAbsolute() && uri.getPath().startsWith("/")) return null; return ("file".equals(uri.getScheme())) ? new FileResourceFactory() : null; } }).anyTimes(); EasyMock.expect( mockAggregator.getModuleBuilder((String) EasyMock.anyObject(), (IResource) EasyMock.anyObject())) .andAnswer(new IAnswer<IModuleBuilder>() { public IModuleBuilder answer() throws Throwable { String mid = (String) EasyMock.getCurrentArguments()[0]; return mid.contains(".") ? new TextModuleBuilder() : new JavaScriptModuleBuilder(); } }).anyTimes(); final Ref<IConfig> cfgRef = configRef; EasyMock.expect(mockAggregator.getConfig()).andAnswer(new IAnswer<IConfig>() { public IConfig answer() throws Throwable { return cfgRef.get(); } }).anyTimes(); EasyMock.expect(mockAggregator.getCacheManager()).andAnswer(new IAnswer<ICacheManager>() { public ICacheManager answer() throws Throwable { return cacheMgrRef.get(); } }).anyTimes(); EasyMock.expect(mockAggregator.newModule((String) EasyMock.anyObject(), (URI) EasyMock.anyObject())) .andAnswer(new IAnswer<IModule>() { public IModule answer() throws Throwable { String mid = (String) EasyMock.getCurrentArguments()[0]; URI uri = (URI) EasyMock.getCurrentArguments()[1]; return new ModuleImpl(mid, uri); } }).anyTimes(); EasyMock.expect(mockAggregator.getExecutors()).andAnswer(new IAnswer<IExecutors>() { public IExecutors answer() throws Throwable { return executorsRef.get(); } }).anyTimes(); EasyMock.expect(mockAggregator.newLayerCache()).andAnswer(new IAnswer<ILayerCache>() { public ILayerCache answer() throws Throwable { return new LayerCacheImpl(mockAggregator); } }).anyTimes(); EasyMock.expect(mockAggregator.newModuleCache()).andAnswer(new IAnswer<IModuleCache>() { public IModuleCache answer() throws Throwable { return new ModuleCacheImpl(); } }).anyTimes(); EasyMock.expect(mockAggregator.newGzipCache()).andAnswer(new IAnswer<IGzipCache>() { public IGzipCache answer() throws Throwable { return new GzipCacheImpl(); } }).anyTimes(); EasyMock.expect(mockAggregator.substituteProps((String) EasyMock.anyObject())) .andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return (String) EasyMock.getCurrentArguments()[0]; } }).anyTimes(); EasyMock.expect(mockAggregator.substituteProps((String) EasyMock.anyObject(), (IAggregator.SubstitutionTransformer) EasyMock.anyObject())).andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return (String) EasyMock.getCurrentArguments()[0]; } }).anyTimes(); EasyMock.expect(mockAggregator.getInitParams()).andAnswer(new IAnswer<InitParams>() { public InitParams answer() throws Throwable { return aggInitParams; } }).anyTimes(); EasyMock.expect( mockAggregator.buildAsync(EasyMock.isA(Callable.class), EasyMock.isA(HttpServletRequest.class))) .andAnswer((IAnswer) new IAnswer<Future<?>>() { @Override public Future<?> answer() throws Throwable { Callable<?> builder = (Callable<?>) EasyMock.getCurrentArguments()[0]; return executorsRef.get().getBuildExecutor().submit(builder); } }).anyTimes(); return mockAggregator; }