public Class Revert(String reference) { URI uri = new URI(reference); String domain = uri.getHost(); String path = uri.getPath(); String[] list = domain.split("\\."); if(list.length > 1) { domain = list[1] + "." + list[0]; } else { domain = list[0]; } String type = domain + path.replaceAll("\\/+", "."); return Class.forName(type); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception public virtual string getRaw(string hostname, int port, string uriPath, string mimeType) { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.addRequestProperty("Accept", mimeType); var str = new StringBuilder(); Stream @in = new BufferedInputStream(connection.getInputStream()); try { for (;;) { var b = @in.Read(); if (b < 0) { break; } str.Append((char) (b & 0xff)); } } finally { CloseableUtils.closeQuietly(@in); } return str.ToString(); }
public void OnItemSelected(Presenter.ViewHolder itemViewHolder, Java.Lang.Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item is Movie) { mBackgroundURI = ((Movie)item).GetBackgroundImageURI (); StartBackgroundTimer (); } }
public void AddAuthentication(AuthenticationBase AAuthentication, URI AUrl) { AuthenticationItem TempItem = new AuthenticationItem(); for (int i = 0; i < AAuthentication.Params.Count; i++) { TempItem.Params.Add(AAuthentication.Params.Names(i), AAuthentication.Params.ValueFromIndex(i)); } TempItem.Url = new URI(AUrl.URIString); _Authentications.Add(TempItem); }
public override void EnterFunctionDeclarationHeader(CodeElementsParser.FunctionDeclarationHeaderContext context) { var visibility = context.PUBLIC() != null ? AccessModifier.Public : AccessModifier.Private; QualifiedName name = null; if (context.UserDefinedWord() != null) { var token = ParseTreeUtils.GetTokenFromTerminalNode(context.UserDefinedWord()); name = new URI(token.Text); } Context = context; CodeElement = new FunctionDeclarationHeader(name, visibility); }
/// <summary>Searches the query string for the first value with the given key.</summary> /// <remarks>Searches the query string for the first value with the given key.</remarks> /// <param name="key">which will be encoded</param> /// <exception cref="System.NotSupportedException">if this isn't a hierarchical URI</exception> /// <exception cref="System.ArgumentNullException">if key is null</exception> /// <returns>the decoded value or null if no parameter is found</returns> public static string GetQueryParameter(URI uri, string key) { if (uri.IsOpaque()) { throw new NotSupportedException(NotHierarchical); } if (key == null) { throw new ArgumentNullException("key"); } string query = uri.GetRawQuery(); if (query == null) { return null; } string encodedKey = Encode(key, null); int length = query.Length; int start = 0; do { int nextAmpersand = query.IndexOf('&', start); int end = nextAmpersand != -1 ? nextAmpersand : length; int separator = query.IndexOf('=', start); if (separator > end || separator == -1) { separator = end; } if (separator - start == encodedKey.Length && query.RegionMatches(start, encodedKey , 0, encodedKey.Length)) { if (separator == end) { return string.Empty; } else { string encodedValue = Sharpen.Runtime.Substring(query, separator + 1, end); return Decode(encodedValue, true, Sharpen.Extensions.GetEncoding(Utf8Encoding)); } } // Move start to end of name. if (nextAmpersand != -1) { start = nextAmpersand + 1; } else { break; } } while (true); return null; }
private void SwitchToMaster() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final CancellationHandle cancellationHandle = new CancellationHandle(); CancellationHandle cancellationHandle = new CancellationHandle(); StartModeSwitching(() => { if (_currentTargetState != HighAvailabilityMemberState.ToMaster) { return; } // We just got scheduled. Maybe we are already obsolete - test if (cancellationHandle.CancellationRequested()) { _msgLog.info("Switch to master cancelled on start."); return; } _componentSwitcher.switchToMaster(); if (cancellationHandle.CancellationRequested()) { _msgLog.info("Switch to master cancelled before ha communication started."); return; } _haCommunicationLife.shutdown(); _haCommunicationLife = new LifeSupport(); try { _masterHaURI = _switchToMaster.switchToMaster(_haCommunicationLife, _me); _canAskForElections.set(true); } catch (Exception e) { _msgLog.error("Failed to switch to master", e); /* * If the attempt to switch to master fails, then we must not try again. We'll trigger an election * and if we are elected again, we'll try again. We differentiate between this case and the case where * we simply receive another election result while switching hasn't completed yet by setting the * currentTargetState as follows: */ _currentTargetState = HighAvailabilityMemberState.Pending; // Since this master switch failed, elect someone else _election.demote(_instanceId); } }, cancellationHandle); }
private void ConstructHttpServerURI(QJournalProtocolProtos.GetJournalStateResponseProto ret) { if (ret.HasFromURL()) { URI uri = URI.Create(ret.GetFromURL()); httpServerURL = GetHttpServerURI(uri.GetScheme(), uri.GetPort()); } else { httpServerURL = GetHttpServerURI("http", ret.GetHttpPort()); } }
/// <summary>Create a new HdfsAdmin client.</summary> /// <param name="uri">the unique URI of the HDFS file system to administer</param> /// <param name="conf">configuration</param> /// <exception cref="System.IO.IOException">in the event the file system could not be created /// </exception> public HdfsAdmin(URI uri, Configuration conf) { FileSystem fs = FileSystem.Get(uri, conf); if (!(fs is DistributedFileSystem)) { throw new ArgumentException("'" + uri + "' is not an HDFS URI."); } else { dfs = (DistributedFileSystem)fs; } }
/// <exception cref="System.IO.IOException"/> internal static IList <AsyncLogger> CreateLoggers(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory factory) { IList <AsyncLogger> ret = Lists.NewArrayList(); IList <IPEndPoint> addrs = GetLoggerAddresses(uri); string jid = ParseJournalId(uri); foreach (IPEndPoint addr in addrs) { ret.AddItem(factory.CreateLogger(conf, nsInfo, jid, addr)); } return(ret); }
private static URI RemoveAuthority(URI uri) { try { uri = new URI(uri.GetScheme(), string.Empty, uri.GetPath(), uri.GetQuery(), uri.GetFragment ()); } catch (URISyntaxException e) { throw new ArgumentException(e.GetLocalizedMessage()); } return(uri); }
public RestRequest(URI baseUri, string username, string password) { this._baseUri = UriWithoutSlash(baseUri); if (!string.ReferenceEquals(username, null)) { _client = Client.create(); _client.addFilter(new HTTPBasicAuthFilter(username, password)); } else { _client = _defaultClient; } }
public virtual void TestGetProviderViaURI() { Configuration conf = new Configuration(false); Path jksPath = new Path(testRootDir.ToString(), "test.jks"); URI uri = new URI(JavaKeyStoreProvider.SchemeName + "://file" + jksPath.ToUri()); KeyProvider kp = KeyProviderFactory.Get(uri, conf); NUnit.Framework.Assert.IsNotNull(kp); Assert.Equal(typeof(JavaKeyStoreProvider), kp.GetType()); uri = new URI("foo://bar"); kp = KeyProviderFactory.Get(uri, conf); NUnit.Framework.Assert.IsNull(kp); }
/// <summary> /// Returns a list of /// <see cref="Apache.Http.NameValuePair">NameValuePairs</see> /// as built from the URI's query portion. For example, a URI /// of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for /// b=2, and one for c=3. By convention, /// <code>'&'</code> /// and /// <code>';'</code> /// are accepted as parameter separators. /// <p> /// This is typically useful while parsing an HTTP PUT. /// This API is currently only used for testing. /// </summary> /// <param name="uri">URI to parse</param> /// <param name="charset">Charset name to use while parsing the query</param> /// <returns> /// a list of /// <see cref="Apache.Http.NameValuePair">Apache.Http.NameValuePair</see> /// as built from the URI's query portion. /// </returns> public static IList <NameValuePair> Parse(URI uri, string charset) { string query = uri.GetRawQuery(); if (query != null && query.Length > 0) { IList <NameValuePair> result = new AList <NameValuePair>(); Scanner scanner = new Scanner(query); Parse(result, scanner, QpSepPattern, charset); return(result); } return(Sharpen.Collections.EmptyList()); }
public virtual void TestHsftpCustomUriPortWithCustomDefaultPorts() { Configuration conf = new Configuration(); conf.SetInt(DFSConfigKeys.DfsNamenodeHttpPortKey, 123); conf.SetInt(DFSConfigKeys.DfsNamenodeHttpsPortKey, 456); URI uri = URI.Create("hsftp://localhost:789"); HsftpFileSystem fs = (HsftpFileSystem)FileSystem.Get(uri, conf); NUnit.Framework.Assert.AreEqual(456, fs.GetDefaultPort()); NUnit.Framework.Assert.AreEqual(uri, fs.GetUri()); NUnit.Framework.Assert.AreEqual("127.0.0.1:789", fs.GetCanonicalServiceName()); }
public virtual void TestTimeout() { Configuration conf = new Configuration(); URI uri = URI.Create("hftp://localhost"); HftpFileSystem fs = (HftpFileSystem)FileSystem.Get(uri, conf); URLConnection conn = fs.connectionFactory.OpenConnection(new Uri("http://localhost" )); NUnit.Framework.Assert.AreEqual(URLConnectionFactory.DefaultSocketTimeout, conn.GetConnectTimeout ()); NUnit.Framework.Assert.AreEqual(URLConnectionFactory.DefaultSocketTimeout, conn.GetReadTimeout ()); }
internal ClusterInstance(Executor stateMachineExecutor, LogProvider logging, MultiPaxosServerFactory factory, ProtocolServer server, MultiPaxosContext ctx, InMemoryAcceptorInstanceStore acceptorInstanceStore, ProverTimeouts timeouts, ClusterInstanceInput input, ClusterInstanceOutput output, URI uri) { this._stateMachineExecutor = stateMachineExecutor; this._logging = logging; this._factory = factory; this._server = server; this._ctx = ctx; this._acceptorInstanceStore = acceptorInstanceStore; this._timeouts = timeouts; this._input = input; this._output = output; this._uri = uri; }
/// <summary> /// Returns a boolean to denote whether a cache file is visible to all(public) /// or not /// </summary> /// <param name="conf"/> /// <param name="uri"/> /// <returns>true if the path in the uri is visible to all, false otherwise</returns> /// <exception cref="System.IO.IOException"/> internal static bool IsPublic(Configuration conf, URI uri, IDictionary <URI, FileStatus > statCache) { FileSystem fs = FileSystem.Get(uri, conf); Path current = new Path(uri.GetPath()); //the leaf level file should be readable by others if (!CheckPermissionOfOther(fs, current, FsAction.Read, statCache)) { return(false); } return(AncestorsHaveExecutePermissions(fs, current.GetParent(), statCache)); }
public void FileConstructorTest1() { URI uri = new URI("file://C:/1.txt"); // TODO: Initialize to an appropriate value try { File target = new File(uri); Assert.Fail("Wenn wir den Konstruktor implementieren, dann auch die Testmethode"); } catch (java.lang.UnsupportedOperationException) { } }
public override void MemberIsAvailable(string role, URI roleUri, StoreId storeId) { try { MemberIsAvailable message = new MemberIsAvailable(role, _myId, _serverClusterId, roleUri, storeId); Payload payload = Serializer.broadcast(message); _atomicBroadcast.broadcast(payload); } catch (Exception e) { _log.warn("Could not distribute member availability", e); } }
public virtual void TestPositiveListFilesNotEndInColon() { // re-initialize the har file system with host name // make sure the qualified path name does not append ":" at the end of host name URI uri = new URI("har://file-localhost" + harPath.ToString()); harFileSystem.Initialize(uri, conf); Path p1 = new Path("har://file-localhost" + harPath.ToString()); Path p2 = harFileSystem.MakeQualified(p1); Assert.True(p2.ToUri().ToString().StartsWith("har://file-localhost/" )); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldOpenBoltPort() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldOpenBoltPort() { // given using (ServerControls controls = GetTestServerBuilder(TestDir.directory()).newServer()) { URI uri = controls.BoltURI(); // when (new SocketConnection()).connect(new HostnamePort(uri.Host, uri.Port)); // then no exception } }
public override void LeftCluster(InstanceId instanceId, URI member) { // Notify unavailability of members outerInstance.Listeners.notify(listener => { foreach (MemberIsAvailable memberIsAvailable in outerInstance.clusterMembersSnapshot.GetCurrentAvailable(instanceId)) { listener.memberIsUnavailable(memberIsAvailable.Role, instanceId); } }); outerInstance.clusterMembersSnapshot.UnavailableMember(instanceId); }
private void TuneIn() { var parameters = new RequestParameters { ["station"] = URI.ToString() }; var doc = (new Request("radio.tune", Session, parameters)).Execute(); Title = Extract(doc, "name"); tunedIn = true; }
public virtual void TestGetProxyUriFromPluginsReturnsValidUriWhenAble() { ApplicationId id = BuilderUtils.NewApplicationId(6384623l, 5); IList <TrackingUriPlugin> list = Lists.NewArrayListWithExpectedSize(2); // Insert a plugin that returns null. list.AddItem(new _TrackingUriPlugin_108()); // Insert a plugin that returns a valid URI. list.AddItem(new _TrackingUriPlugin_114()); URI result = ProxyUriUtils.GetUriFromTrackingPlugins(id, list); NUnit.Framework.Assert.IsNotNull(result); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void put(java.net.URI uri, java.util.Map<String, java.util.List<String>> responseHeaders) throws java.io.IOException public override void put(URI uri, IDictionary <string, IList <string> > responseHeaders) { CookieManager cookieManager = @delegate.get(); if (cookieManager != null) { cookieManager.put(uri, responseHeaders); } else { base.put(uri, responseHeaders); } }
/// <exception cref="System.Exception"/> internal static TestViewFileSystemDelegationTokenSupport.FakeFileSystem SetupFileSystem (URI uri, Type clazz) { string scheme = uri.GetScheme(); conf.Set("fs." + scheme + ".impl", clazz.FullName); TestViewFileSystemDelegationTokenSupport.FakeFileSystem fs = (TestViewFileSystemDelegationTokenSupport.FakeFileSystem )FileSystem.Get(uri, conf); // mount each fs twice, will later ensure 1 token/fs ConfigUtil.AddLink(conf, "/mounts/" + scheme + "-one", fs.GetUri()); ConfigUtil.AddLink(conf, "/mounts/" + scheme + "-two", fs.GetUri()); return(fs); }
public virtual void TestAbsolutePathAsURI() { URI u = null; u = Util.StringAsURI(AbsolutePathWindows); NUnit.Framework.Assert.IsNotNull("Uri should not be null for Windows path" + AbsolutePathWindows , u); NUnit.Framework.Assert.AreEqual(UriFileSchema, u.GetScheme()); u = Util.StringAsURI(AbsolutePathUnix); NUnit.Framework.Assert.IsNotNull("Uri should not be null for Unix path" + AbsolutePathUnix , u); NUnit.Framework.Assert.AreEqual(UriFileSchema, u.GetScheme()); }
/// <summary> /// Returns a reference to an existing {@code FileSystem}. /// /// <para> This method iterates over the {@link FileSystemProvider#installedProviders() /// installed} providers to locate the provider that is identified by the URI /// <seealso cref="URI#getScheme scheme"/> of the given URI. URI schemes are compared /// without regard to case. The exact form of the URI is highly provider /// dependent. If found, the provider's {@link FileSystemProvider#getFileSystem /// getFileSystem} method is invoked to obtain a reference to the {@code /// FileSystem}. /// /// </para> /// <para> Once a file system created by this provider is {@link FileSystem#close /// closed} it is provider-dependent if this method returns a reference to /// the closed file system or throws <seealso cref="FileSystemNotFoundException"/>. /// If the provider allows a new file system to be created with the same URI /// as a file system it previously created then this method throws the /// exception if invoked after the file system is closed (and before a new /// instance is created by the <seealso cref="#newFileSystem newFileSystem"/> method). /// /// </para> /// <para> If a security manager is installed then a provider implementation /// may require to check a permission before returning a reference to an /// existing file system. In the case of the {@link FileSystems#getDefault /// default} file system, no permission check is required. /// /// </para> /// </summary> /// <param name="uri"> the URI to locate the file system /// </param> /// <returns> the reference to the file system /// </returns> /// <exception cref="IllegalArgumentException"> /// if the pre-conditions for the {@code uri} parameter are not met </exception> /// <exception cref="FileSystemNotFoundException"> /// if the file system, identified by the URI, does not exist </exception> /// <exception cref="ProviderNotFoundException"> /// if a provider supporting the URI scheme is not installed </exception> /// <exception cref="SecurityException"> /// if a security manager is installed and it denies an unspecified /// permission </exception> public static FileSystem GetFileSystem(URI uri) { String scheme = uri.Scheme; foreach (FileSystemProvider provider in FileSystemProvider.InstalledProviders()) { if (scheme.EqualsIgnoreCase(provider.Scheme)) { return(provider.GetFileSystem(uri)); } } throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found"); }
private string TrimTrailingSlash(URI uri) { string result = uri.ToString(); if (result.EndsWith("/", StringComparison.Ordinal)) { return(result.Substring(0, result.Length - 1)); } else { return(result); } }
private void Initialize(string scheme, string authority, string path, string fragment ) { try { this.uri = new URI(scheme, authority, NormalizePath(scheme, path), null, fragment ).Normalize(); } catch (URISyntaxException e) { throw new ArgumentException(e); } }
public static void SetUp() { conf = new Configuration(); conf.Set(DFSConfigKeys.DfsWebhdfsAuthenticationFilterKey, typeof(TestWebHdfsWithAuthenticationFilter.CustomizedFilter ).FullName); conf.Set(DFSConfigKeys.DfsNamenodeHttpAddressKey, "localhost:0"); cluster = new MiniDFSCluster.Builder(conf).NumDataNodes(1).Build(); IPEndPoint addr = cluster.GetNameNode().GetHttpAddress(); fs = FileSystem.Get(URI.Create("webhdfs://" + NetUtils.GetHostPortString(addr)), conf); cluster.WaitActive(); }
static ClusterConfigurationTest() { try { Neo4jServer1Uri = new URI("neo4j://server1"); Neo4jServerId = new InstanceId(1); } catch (URISyntaxException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }
private URI CreateHaURI <T1>(URI me, Server <T1> server) { InetSocketAddress serverSocketAddress = server.SocketAddress; string hostString = ServerUtil.getHostString(serverSocketAddress); string host = IsWildcard(hostString) ? me.Host : hostString; host = EnsureWrapForIpv6Uri(host); InstanceId serverId = Config.get(ClusterSettings.server_id); return(URI.create("ha://" + host + ":" + serverSocketAddress.Port + "?serverId=" + serverId)); }
internal virtual URI BuildUri(string uri) { URI unprefixedUri = URI.create(uri); if (unprefixedUri.Absolute) { return(unprefixedUri); } else { return(URI.create(BaseUri + uri)); } }
/// <summary>Parse the file system URI out of the provided token.</summary> public static URI GetServiceUriFromToken <_T0>(string scheme, Org.Apache.Hadoop.Security.Token.Token <_T0> token) where _T0 : TokenIdentifier { string tokStr = token.GetService().ToString(); string prefix = BuildTokenServicePrefixForLogicalUri(scheme); if (tokStr.StartsWith(prefix)) { tokStr = tokStr.ReplaceFirst(prefix, string.Empty); } return(URI.Create(scheme + "://" + tokStr)); }
private bool saveServer() { database = dbhelper.WritableDatabase; bool result = false; try { URI uri = new URI(FindViewById<EditText>(Resource.Id.edit_server_host).Text); string name = FindViewById<EditText>(Resource.Id.edit_server_name).Text; string scheme = null; string host = uri.Host; string port = FindViewById<EditText>(Resource.Id.edit_server_port).Text; string user = FindViewById<EditText>(Resource.Id.edit_server_user).Text; string pass = FindViewById<EditText>(Resource.Id.edit_server_pass).Text; if (uri.Scheme == null) { scheme = "http"; host = uri.SchemeSpecificPart; } else { scheme = uri.Scheme; } if (name.Length == 0 || host.Length == 0 || port.Length == 0 || user.Length == 0) { Toast.MakeText(this, "One or more fields are empty", ToastLength.Short).Show(); return false; } ContentValues values = new ContentValues(); values.Put(YastroidOpenHelper.SERVERS_NAME, name); values.Put(YastroidOpenHelper.SERVERS_SCHEME, scheme); values.Put(YastroidOpenHelper.SERVERS_HOST, host); values.Put(YastroidOpenHelper.SERVERS_PORT, port); values.Put(YastroidOpenHelper.SERVERS_USER, user); if(pass.Length == 0 ) values.Put(YastroidOpenHelper.SERVERS_PASS, s.getPass()); else values.Put(YastroidOpenHelper.SERVERS_PASS, pass); values.Put(YastroidOpenHelper.SERVERS_GROUP, s.getGroupId()); database.Update(YastroidOpenHelper.SERVERS_TABLE_NAME, values, YastroidOpenHelper.SERVERS_ID + "=" + s.getId(), null); database.Close(); Log.Info("ARRAY", "WebYaST server " + name + " has been updated."); result = true; } catch (Exception e) { Log.Error("BACKGROUND_PROC", e.Message); } Toast.MakeText(this, "Server Updated", ToastLength.Short).Show(); return result; }
/// <param name="propertyFilePath"> /// </param> /// <returns> void /// /// @Description: 使用TOMCAT方式来导入 /// @author liaoqiqi /// @date 2013-6-19 </returns> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static java.util.Properties loadWithTomcatMode(final String propertyFilePath) throws Exception //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: private static Properties loadWithTomcatMode(string propertyFilePath) { Properties props = new Properties(); try { // 先用TOMCAT模式进行导入 // http://blog.csdn.net/minfree/article/details/1800311 // http://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java URL url = ClassLoaderUtil.Loader.getResource(propertyFilePath); URI uri = new URI(url.ToString()); props.load(new System.IO.StreamReader(new System.IO.FileStream(uri.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read), Encoding.UTF8)); } catch (Exception) { // http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar props.load(new System.IO.StreamReader(ClassLoaderUtil.Loader.getResourceAsStream(propertyFilePath), Encoding.UTF8)); } return props; }
public CacheRequest put(URI arg0, URLConnection arg1) { return Instance.CallMethod<CacheRequest>("put", "(Ljava/net/URI;Ljava/net/URLConnection;)Ljava/net/CacheRequest;", arg0, arg1); }
protected void UpdateBackground (URI uri) { Picasso.With (this.Activity) .Load (uri.ToString ()) .Resize (mMetrics.WidthPixels, mMetrics.HeightPixels) .CenterCrop () .Error (mDefaultBackground) .Into (mBackgroundTarget); }
public void OnItemSelected (Java.Lang.Object item, Row row) { if (item is Movie) { mBackgroundURI = ((Movie)item).GetBackgroundImageURI (); StartBackgroundTimer (); } }
private bool HandleManualyRedirect () { Header redirectHeader = _method.getResponseHeader ("location"); if (redirectHeader == null) { // See comments above for the error >= 400 _response.ReadAllAndClose (); //this.Abort(); throw new WebException ("Got response code " + _response.StatusCode + ", but no location provided", null, WebExceptionStatus.ProtocolError, _response); } mainsoft.apache.commons.httpclient.HttpMethod originalMethod = _method; try { string location = redirectHeader.getValue (); URI currentUri = _method.getURI (); URI redirectUri = null; redirectUri = new URI (location, true); if (redirectUri.isRelativeURI ()) { //location is incomplete, use current values for defaults redirectUri = new URI (currentUri, redirectUri); } _method = new GetMethod (); foreach(Header h in originalMethod.getRequestHeaders()) _method.addRequestHeader(h); _method.setURI (redirectUri); InternalExecuteMethod (); return true; } catch (URIException e) { _method = originalMethod; return false; } }
public void put(URI arg0, Map<String, List<String>> arg1) { Instance.CallMethod("put", "(Ljava/net/URI;Ljava/util/Map;)V", arg0, arg1); }
public CacheResponse @get(URI arg0, String arg1, Map<String, List<String>> arg2) { return Instance.CallMethod<CacheResponse>("get", "(Ljava/net/URI;Ljava/lang/String;Ljava/util/Map;)Ljava/net/CacheResponse;", arg0, arg1, arg2); }
/// <summary> /// Handle a 3xx redirect status. /// </summary> /// <param name="state"> /// The state. /// </param> /// <param name="response"> /// The response. /// </param> /// <param name="statusCode"> /// The status Code. /// </param> private void HandleRedirect(State state, HttpWebResponse response, HttpStatusCode statusCode) { Debug.WriteLine("got HTTP redirect " + statusCode); if (state.RedirectCount >= DownloaderService.MaxRedirects) { throw new StopRequestException(ExpansionDownloadStatus.TooManyRedirects, "too many redirects"); } string header = response.GetResponseHeader("Location"); if (header == null) { return; } Debug.WriteLine("Redirecting to " + header); string newUri; try { newUri = new URI(this.downloadInfo.Uri).Resolve(new URI(header)).ToString(); } catch (URISyntaxException) { Debug.WriteLine("Couldn't resolve redirect URI {0} for {1}", header, this.downloadInfo.Uri); throw new StopRequestException(ExpansionDownloadStatus.HttpDataError, "Couldn't resolve redirect URI"); } ++state.RedirectCount; state.RequestUri = newUri; if ((int)statusCode == 301 || (int)statusCode == 303) { // use the new URI for all future requests (should a retry/resume be necessary) state.NewUri = newUri; } throw new RetryDownloadException(); }
public void initialize(URI uri, Configuration conf) { setConf(conf); }
public void SetURI(URI uri) { this.Uri = uri; }
/* **************************************************************************** * testProxy() **************************************************************************** */ /** * */ public void testProxy() { URI oProxyURI = null; try { oProxyURI = new URI("http://xri.epok.net/proxy"); } catch (URISyntaxException e) { fail("Unexpected initialization error"); } Resolver oResolver = new TestResolver(); oResolver.setProxyURI(oProxyURI); oResolver.setMaxHttpRedirects(0); // should not work - not enough descriptors try { XRD oDesc = oResolver.resolveAuthToXRD("xri://@!foo!bar!baz", new TrustType(), true); assertFalse("Should get a PartialResolutionException", oDesc.getStatusCode().Equals(Status.SUCCESS)); } catch (Exception e) { if (e is PartialResolutionException) { String stat1 = null, stat2 = null, stat3 = null; PartialResolutionException pe = (PartialResolutionException)e; System.err.println(pe.getPartialXRDS().toString()); assertTrue("Should contain 3 XRDs, got " + pe.getPartialXRDS().getNumChildren() + " instead", pe.getPartialXRDS().getNumChildren() == 3); try { stat1 = pe.getPartialXRDS().getDescriptorAt(0).getStatusCode(); stat2 = pe.getPartialXRDS().getDescriptorAt(1).getStatusCode(); stat3 = pe.getPartialXRDS().getDescriptorAt(2).getStatusCode(); } catch (Exception e1) { assertTrue("Got exception: " + e1.getMessage(), false); } assertTrue("First XRD should be successful", stat1.Equals(Status.SUCCESS)); assertTrue("Second XRD should be successful", stat2.Equals(Status.SUCCESS)); assertTrue("Third XRD should be a failure", stat3.Equals(Status.AUTH_RES_NOT_FOUND)); } else { fail("Got exception while trying to resolve via proxy " + e); e.printStackTrace(); } } // should not work - too many descriptors /*** [wil] test disabled - proxy resolution currently does not validate the number of XRDs returned. try { XRD oDesc = oResolver.resolveAuthToXRD("xri://@!foo", new TrustType(), true); assertFalse("Should get a failure code for too many XRDs", oDesc.getStatusCode().Equals(Status.SUCCESS)); } catch (Exception oEx) { fail("Got exception while trying to resolve via proxy " + oEx); } */ // should work as (null response) try { XRD oDesc = oResolver.resolveAuthToXRD("xri://@!foo!nonexistent", new TrustType(), true); assertTrue( "Should not have obtained XRD from proxy", oDesc == null); } catch (Exception e) { if (e is PartialResolutionException) { PartialResolutionException pe = (PartialResolutionException)e; String stat = null; try { stat = pe.getPartialXRDS().getDescriptorAt(0).getStatusCode(); } catch (Exception e1) { assertTrue("got exception: " + e1.getMessage(), false); } assertTrue("First XRD should fail", stat.Equals(Status.AUTH_RES_NOT_FOUND)); } else { fail("Got exception while trying to resolve via proxy " + e); } } // should work try { XRD oDesc = oResolver.resolveAuthToXRD("xri://@!foo!bar", new TrustType(), false); assertTrue( "Failed to obtain XRD from proxy", oDesc != null); } catch (Exception oEx) { fail("Got exception while trying to resolve via proxy " + oEx); } }
// throws XRIResolutionException protected InputStream getDataFromURI(URI oURI, string query, ResolverFlags flags, ResolverState state) { // the path better be empty if ((oURI.getPath() != null) && (oURI.getPath().Length > 0)) return null; XRD oDesc = new XRD(); XRI oExternal = new XRI("xri://@foo"); oDesc.addRef(new Ref(oExternal.toString())); XRDS oDescs = new XRDS(); oDescs.add(oDesc); state.pushResolved(oURI.toString(), flags.toString(), oDesc.toString(), oURI); return new ByteArrayInputStream(oDescs.toString().getBytes()); }
public List<Proxy> @select(URI arg0) { return Instance.CallMethod<List<Proxy>>("select", "(Ljava/net/URI;)Ljava/util/List;", arg0); }
//throws XRIResolutionException /* ************************************************************************ * getDataFromURI() ************************************************************************ */ /** * */ protected InputStream getDataFromURI(URI uri, String query, ResolverFlags flags, ResolverState state) { // if we got the nonexistent "command" return a not found if (uri.getPath().indexOf("!nonexistent") >= 0) { XRD xrd = new XRD(); xrd.setQuery("!nonexistent"); xrd.setStatus(new Status(Status.AUTH_RES_NOT_FOUND)); XRDS xrds = new XRDS(); xrds.add(xrd); return new ByteArrayInputStream(xrds.toString().getBytes()); } XRDS oDescs = new XRDS(); // just the same response always XRD oFoo = new XRD(); oFoo.setQuery("!foo"); oFoo.setStatus(new Status(Status.SUCCESS)); oDescs.add(oFoo); XRD oBar = new XRD(); oBar.setQuery("!bar"); oBar.setStatus(new Status(Status.SUCCESS)); oDescs.add(oBar); if (uri.getPath().indexOf("!baz") > 0) { XRD baz = new XRD(); baz.setQuery("!baz"); baz.setStatus(new Status(Status.AUTH_RES_NOT_FOUND, "Not found")); oDescs.add(baz); } return new ByteArrayInputStream(oDescs.toString().getBytes()); }
public Map<String, List<String>> @get(URI arg0, Map<String, List<String>> arg1) { return Instance.CallMethod<Map<String, List<String>>>("get", "(Ljava/net/URI;Ljava/util/Map;)Ljava/util/Map;", arg0, arg1); }
/** * * @param qxri QXRI that was resolved * @param xrds XRDS document received * @param uri URI queried to resolve the QXRI */ public void pushResolved(String qxri, String trustType, String xrds, URI uri) { ResolverStep step = new ResolverStep(qxri, trustType, xrds, null, uri); steps.add(step); numRequests++; numBytesReceived += xrds.length(); }
public void testConstructURI() { Resolver resolver = new Resolver(); string qxri = "xri://@a*b*c/d/e?f=g"; try { URI sepURI = new URI("http://example.com/hello"); string result = resolver.constructURI(sepURI, "local", new XRI(qxri)); assertTrue("Invalid constructed URI for append=local '" + result + "'", result.Equals(sepURI.toString() + "/d/e?f=g")); result = resolver.constructURI(sepURI, "qxri", new XRI(qxri)); assertTrue("Invalid constructed URI for append=qxri '" + result + "'", result.Equals(sepURI.toString() + "@a*b*c/d/e?f=g")); Logger.Info("result = " + result); } catch (Exception oEx) { fail("Got wrong exception while trying to resolve IRI " + oEx); } }
public URI Relativize(URI toUri) { throw new System.NotImplementedException(); }
public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) { Instance.CallMethod("connectFailed", "(Ljava/net/URI;Ljava/net/SocketAddress;Ljava/io/IOException;)V", arg0, arg1, arg2); }
public void SetLibrary(string libname) { Name = new URI(libname + "." + Name); }
public static Path @get(URI arg0) { return Static.CallMethod<Path>(typeof(Paths), "get", "(Ljava/net/URI;)Ljava/nio/file/Path;", arg0); }