private static string convertStreamToString(InputStream @is) { BufferedReader reader = new BufferedReader(new InputStreamReader(@is)); StringBuilder sb = new StringBuilder(); string line = null; try { while ((line = reader.ReadLine()) != null) { sb.Append((line + "\n")); } } catch (IOException e) { Log.W("LOG", e.GetMessage()); } finally { try { @is.Close(); } catch (IOException e) { Log.W("LOG", e.GetMessage()); } } return sb.ToString(); }
/// <exception cref="System.IO.IOException"></exception> protected internal override void DoDisconnect(bool hard) { try { if (Sessions != null) { foreach (var ssn in Sessions) { ssn?.Logoff(hard); } } Out?.Close(); In?.Close(); //Socket.`Close` method deleted //Socket.Close(); Socket?.Shutdown(SocketShutdown.Both); Socket?.Dispose(); } finally { Digest = null; Socket = null; TconHostName = null; } }
/// <exception cref="System.IO.IOException"></exception> private DirCache CreateTemporaryIndex(ObjectId headId, DirCache index) { ObjectInserter inserter = null; // get DirCacheEditor to modify the index if required DirCacheEditor dcEditor = index.Editor(); // get DirCacheBuilder for newly created in-core index to build a // temporary index for this commit DirCache inCoreIndex = DirCache.NewInCore(); DirCacheBuilder dcBuilder = inCoreIndex.Builder(); onlyProcessed = new bool[only.Count]; bool emptyCommit = true; TreeWalk treeWalk = new TreeWalk(repo); int dcIdx = treeWalk.AddTree(new DirCacheIterator(index)); int fIdx = treeWalk.AddTree(new FileTreeIterator(repo)); int hIdx = -1; if (headId != null) { hIdx = treeWalk.AddTree(new RevWalk(repo).ParseTree(headId)); } treeWalk.Recursive = true; while (treeWalk.Next()) { string path = treeWalk.PathString; // check if current entry's path matches a specified path int pos = LookupOnly(path); CanonicalTreeParser hTree = null; if (hIdx != -1) { hTree = treeWalk.GetTree <CanonicalTreeParser>(hIdx); } if (pos >= 0) { // include entry in commit DirCacheIterator dcTree = treeWalk.GetTree <DirCacheIterator>(dcIdx); FileTreeIterator fTree = treeWalk.GetTree <FileTreeIterator>(fIdx); // check if entry refers to a tracked file bool tracked = dcTree != null || hTree != null; if (!tracked) { break; } if (fTree != null) { // create a new DirCacheEntry with data retrieved from disk DirCacheEntry dcEntry = new DirCacheEntry(path); long entryLength = fTree.GetEntryLength(); dcEntry.SetLength(entryLength); dcEntry.LastModified = fTree.GetEntryLastModified(); dcEntry.FileMode = fTree.EntryFileMode; bool objectExists = (dcTree != null && fTree.IdEqual(dcTree)) || (hTree != null && fTree.IdEqual(hTree)); if (objectExists) { dcEntry.SetObjectId(fTree.EntryObjectId); } else { // insert object if (inserter == null) { inserter = repo.NewObjectInserter(); } InputStream inputStream = fTree.OpenEntryStream(); try { dcEntry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, entryLength, inputStream) ); } finally { inputStream.Close(); } } // update index dcEditor.Add(new _PathEdit_356(dcEntry, path)); // add to temporary in-core index dcBuilder.Add(dcEntry); if (emptyCommit && (hTree == null || !hTree.IdEqual(fTree))) { // this is a change emptyCommit = false; } } else { // if no file exists on disk, remove entry from index and // don't add it to temporary in-core index dcEditor.Add(new DirCacheEditor.DeletePath(path)); if (emptyCommit && hTree != null) { // this is a change emptyCommit = false; } } // keep track of processed path onlyProcessed[pos] = true; } else { // add entries from HEAD for all other paths if (hTree != null) { // create a new DirCacheEntry with data retrieved from HEAD DirCacheEntry dcEntry = new DirCacheEntry(path); dcEntry.SetObjectId(hTree.EntryObjectId); dcEntry.FileMode = hTree.EntryFileMode; // add to temporary in-core index dcBuilder.Add(dcEntry); } } } // there must be no unprocessed paths left at this point; otherwise an // untracked or unknown path has been specified for (int i = 0; i < onlyProcessed.Length; i++) { if (!onlyProcessed[i]) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().entryNotFoundByPath , only[i])); } } // there must be at least one change if (emptyCommit) { throw new JGitInternalException(JGitText.Get().emptyCommit); } // update index dcEditor.Commit(); // finish temporary in-core index used for this commit dcBuilder.Finish(); return(inCoreIndex); }
protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request) { object fullBody = null; Exception error = null; try { HttpResponse response = httpClient.Execute(request); // add in cookies to global store try { if (httpClient is DefaultHttpClient) { DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient; CouchbaseLiteHttpClientFactory.Instance.AddCookies(defaultHttpClient.GetCookieStore ().GetCookies()); } } catch (Exception e) { Log.E(Database.Tag, "Unable to add in cookies to global store", e); } StatusLine status = response.GetStatusLine(); if (status.GetStatusCode() >= 300) { Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode ())); Log.E(Database.Tag, "Request was for: " + request.ToString()); Log.E(Database.Tag, "Status reason: " + status.GetReasonPhrase()); error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase( )); } else { HttpEntity temp = response.GetEntity(); if (temp != null) { InputStream stream = null; try { stream = temp.GetContent(); fullBody = Manager.GetObjectMapper().ReadValue <object>(stream); } finally { try { stream.Close(); } catch (IOException) { } } } } } catch (ClientProtocolException e) { Log.E(Database.Tag, "client protocol exception", e); error = e; } catch (IOException e) { Log.E(Database.Tag, "io exception", e); error = e; } RespondWithResult(fullBody, error); }
/// <summary> /// Stash the contents on the working directory and index in separate commits /// and reset to the current HEAD commit. /// </summary> /// <remarks> /// Stash the contents on the working directory and index in separate commits /// and reset to the current HEAD commit. /// </remarks> /// <returns>stashed commit or null if no changes to stash</returns> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> public override RevCommit Call() { CheckCallable(); Ref head = GetHead(); ObjectReader reader = repo.NewObjectReader(); try { RevCommit headCommit = ParseCommit(reader, head.GetObjectId()); DirCache cache = repo.LockDirCache(); ObjectInserter inserter = repo.NewObjectInserter(); ObjectId commitId; try { TreeWalk treeWalk = new TreeWalk(reader); treeWalk.Recursive = true; treeWalk.AddTree(headCommit.Tree); treeWalk.AddTree(new DirCacheIterator(cache)); treeWalk.AddTree(new FileTreeIterator(repo)); treeWalk.Filter = AndTreeFilter.Create(new SkipWorkTreeFilter(1), new IndexDiffFilter (1, 2)); // Return null if no local changes to stash if (!treeWalk.Next()) { return(null); } MutableObjectId id = new MutableObjectId(); IList <DirCacheEditor.PathEdit> wtEdits = new AList <DirCacheEditor.PathEdit>(); IList <string> wtDeletes = new AList <string>(); do { AbstractTreeIterator headIter = treeWalk.GetTree <AbstractTreeIterator>(0); DirCacheIterator indexIter = treeWalk.GetTree <DirCacheIterator>(1); WorkingTreeIterator wtIter = treeWalk.GetTree <WorkingTreeIterator>(2); if (headIter != null && indexIter != null && wtIter != null) { if (wtIter.IdEqual(indexIter) || wtIter.IdEqual(headIter)) { continue; } treeWalk.GetObjectId(id, 0); DirCacheEntry entry = new DirCacheEntry(treeWalk.RawPath); entry.SetLength(wtIter.GetEntryLength()); entry.LastModified = wtIter.GetEntryLastModified(); entry.FileMode = wtIter.EntryFileMode; long contentLength = wtIter.GetEntryContentLength(); InputStream @in = wtIter.OpenEntryStream(); try { entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentLength, @in)); } finally { @in.Close(); } wtEdits.AddItem(new _PathEdit_267(entry, entry)); } else { if (indexIter == null) { wtDeletes.AddItem(treeWalk.PathString); } else { if (wtIter == null && headIter != null) { wtDeletes.AddItem(treeWalk.PathString); } } } }while (treeWalk.Next()); string branch = Repository.ShortenRefName(head.GetTarget().GetName()); // Commit index changes NGit.CommitBuilder builder = CreateBuilder(headCommit); builder.TreeId = cache.WriteTree(inserter); builder.Message = MessageFormat.Format(indexMessage, branch, headCommit.Abbreviate (7).Name, headCommit.GetShortMessage()); ObjectId indexCommit = inserter.Insert(builder); // Commit working tree changes if (!wtEdits.IsEmpty() || !wtDeletes.IsEmpty()) { DirCacheEditor editor = cache.Editor(); foreach (DirCacheEditor.PathEdit edit in wtEdits) { editor.Add(edit); } foreach (string path in wtDeletes) { editor.Add(new DirCacheEditor.DeletePath(path)); } editor.Finish(); } builder.AddParentId(indexCommit); builder.Message = MessageFormat.Format(workingDirectoryMessage, branch, headCommit .Abbreviate(7).Name, headCommit.GetShortMessage()); builder.TreeId = cache.WriteTree(inserter); commitId = inserter.Insert(builder); inserter.Flush(); UpdateStashRef(commitId, builder.Author, builder.Message); } finally { inserter.Release(); cache.Unlock(); } // Hard reset to HEAD new ResetCommand(repo).SetMode(ResetCommand.ResetType.HARD).Call(); // Return stashed commit return(ParseCommit(reader, commitId)); } catch (IOException e) { throw new JGitInternalException(JGitText.Get().stashFailed, e); } finally { reader.Release(); } }
/// <exception cref="System.IO.IOException"></exception> internal void List() { IDictionary <string, string> args = new SortedDictionary <string, string>(); if (this.prefix.Length > 0) { args.Put("prefix", this.prefix); } if (!this.entries.IsEmpty()) { args.Put("marker", this.prefix + this.entries[this.entries.Count - 1]); } for (int curAttempt = 0; curAttempt < this._enclosing.maxAttempts; curAttempt++) { HttpURLConnection c = this._enclosing.Open("GET", this.bucket, string.Empty, args ); this._enclosing.Authorize(c); switch (HttpSupport.Response(c)) { case HttpURLConnection.HTTP_OK: { this.truncated = false; this.data = null; XMLReader xr; try { xr = XMLReaderFactory.CreateXMLReader(); } catch (SAXException) { throw new IOException(JGitText.Get().noXMLParserAvailable); } xr.SetContentHandler(this); InputStream @in = c.GetInputStream(); try { xr.Parse(new InputSource(@in)); } catch (SAXException parsingError) { IOException p; p = new IOException(MessageFormat.Format(JGitText.Get().errorListing, this.prefix )); Sharpen.Extensions.InitCause(p, parsingError); throw p; } finally { @in.Close(); } return; } case HttpURLConnection.HTTP_INTERNAL_ERROR: { continue; goto default; } default: { throw this._enclosing.Error("Listing", this.prefix, c); } } } throw this._enclosing.MaxAttempts("Listing", this.prefix); }
/// <summary> /// Invoke the pipeline asynchronously with input. /// </summary> /// <param name="input">input to provide to pipeline. Input is /// used only for synchronous execution</param> /// <param name="syncCall">True if this method is called from /// synchronous invoke else false</param> /// <remarks> /// Results are returned through the <see cref="Pipeline.Output"/> reader. /// </remarks> /// <exception cref="InvalidOperationException"> /// No command is added to pipeline /// </exception> /// <exception cref="InvalidPipelineStateException"> /// PipelineState is not NotStarted. /// </exception> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) InvokeAsync is called on nested pipeline. Nested pipeline /// cannot be executed Asynchronously. /// 3) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// RunspaceState is not Open /// </exception> /// <exception cref="ObjectDisposedException"> /// Pipeline already disposed /// </exception> private void CoreInvoke(IEnumerable input, bool syncCall) { lock (SyncRoot) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); } if (Commands == null || Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); } if (PipelineState != PipelineState.NotStarted) { InvalidPipelineStateException e = new InvalidPipelineStateException ( StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed), PipelineState, PipelineState.NotStarted ); throw e; } if (syncCall && !(InputStream is PSDataCollectionStream <PSObject> || InputStream is PSDataCollectionStream <object>)) { //Method is called from synchronous invoke. if (input != null) { //TO-DO-Add a test make sure that ObjectDisposed //exception is thrown //Write input data in to inputStream and close the input //pipe. If Input stream is already closed an //ObjectDisposed exception will be thrown foreach (object temp in input) { InputStream.Write(temp); } } InputStream.Close(); } SyncInvokeCall = syncCall; //Create event which will be signalled when pipeline execution //is completed/failed/stoped. //Note:Runspace.Close waits for all the running pipeline //to finish. This Event must be created before pipeline is //added to list of running pipelines. This avoids the race condition //where Close is called after pipeline is added to list of //running pipeline but before event is created. PipelineFinishedEvent = new ManualResetEvent(false); //1) Do the check to ensure that pipeline no other // pipeline is running. //2) Runspace object maintains a list of pipelines in //execution. Add this pipeline to the list. RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); //Note: Set PipelineState to Running only after adding pipeline to list //of pipelines in execution. AddForExecution checks that runspace is in //state where pipeline can be run. //StartPipelineExecution raises this event. See Windows Bug 1160481 for //more details. SetPipelineState(PipelineState.Running); } try { //Let the derived class start the pipeline execution. StartPipelineExecution(); } catch (Exception exception) { //If we fail in any of the above three steps, set the correct states. RunspaceBase.RemoveFromRunningPipelineList(this); SetPipelineState(PipelineState.Failed, exception); //Note: we are not raising the events in this case. However this is //fine as user is getting the exception. throw; } }
/// <summary>Close the underlying stream.</summary> /// <exception cref="System.IO.IOException"/> public virtual void Close() { @in.Close(); }
private static void extractFunctionData(FunctionDataCollector fdc, InputStream is1) { XMLReader xr; try { // First up, try the default one xr = XMLReaderFactory.CreateXMLReader(); } catch (SAXException e) { // Try one for java 1.4 System.SetProperty("org.xml.sax.driver", "org.apache.crimson.Parser.XMLReaderImpl"); try { xr = XMLReaderFactory.CreateXMLReader(); } catch (SAXException e2) { throw new RuntimeException(e2); } } xr.SetContentHandler(new EFFDocHandler(fdc)); InputSource inSrc = new InputSource(is1); try { xr.Parse(inSrc); is1.Close(); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } }
/// <summary> /// Executes the /// <code>Add</code> /// command. Each instance of this class should only /// be used for one invocation of the command. Don't call this method twice /// on an instance. /// </summary> /// <returns>the DirCache after Add</returns> /// <exception cref="NGit.Api.Errors.NoFilepatternException"></exception> public override DirCache Call() { if (filepatterns.IsEmpty()) { throw new NoFilepatternException(JGitText.Get().atLeastOnePatternIsRequired); } CheckCallable(); DirCache dc = null; bool addAll = false; if (filepatterns.Contains(".")) { addAll = true; } ObjectInserter inserter = repo.NewObjectInserter(); try { dc = repo.LockDirCache(); DirCacheIterator c; DirCacheBuilder builder = dc.Builder(); TreeWalk tw = new TreeWalk(repo); tw.AddTree(new DirCacheBuildIterator(builder)); if (workingTreeIterator == null) { workingTreeIterator = new FileTreeIterator(repo); } tw.AddTree(workingTreeIterator); tw.Recursive = true; if (!addAll) { tw.Filter = PathFilterGroup.CreateFromStrings(filepatterns); } string lastAddedFile = null; while (tw.Next()) { string path = tw.PathString; WorkingTreeIterator f = tw.GetTree <WorkingTreeIterator>(1); if (tw.GetTree <DirCacheIterator>(0) == null && f != null && f.IsEntryIgnored()) { } else { // file is not in index but is ignored, do nothing // In case of an existing merge conflict the // DirCacheBuildIterator iterates over all stages of // this path, we however want to add only one // new DirCacheEntry per path. if (!(path.Equals(lastAddedFile))) { if (!(update && tw.GetTree <DirCacheIterator>(0) == null)) { c = tw.GetTree <DirCacheIterator>(0); if (f != null) { // the file exists long sz = f.GetEntryLength(); DirCacheEntry entry = new DirCacheEntry(path); if (c == null || c.GetDirCacheEntry() == null || !c.GetDirCacheEntry().IsAssumeValid) { entry.SetLength(sz); entry.LastModified = f.GetEntryLastModified(); entry.FileMode = f.EntryFileMode; InputStream @in = f.OpenEntryStream(); try { entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, sz, @in)); } finally { @in.Close(); } builder.Add(entry); lastAddedFile = path; } else { builder.Add(c.GetDirCacheEntry()); } } else { if (!update) { builder.Add(c.GetDirCacheEntry()); } } } } } } inserter.Flush(); builder.Commit(); SetCallable(false); } catch (IOException e) { throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfAddCommand , e); } finally { inserter.Release(); if (dc != null) { dc.Unlock(); } } return(dc); }
/** * Reads GIF image from stream * * @param is containing GIF file. * @return read status code (0 = no errors) */ public int read(InputStream inputStream, int contentLength) { long startTime = DateTime.Now.Millisecond; if (inputStream != null) { try { int capacity = (contentLength > 0) ? (contentLength + 4096) : 4096; ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity); int nRead; byte[] data = new byte[16384]; while ((nRead = inputStream.Read(data, 0, data.Length)) != -1) { buffer.Write(data, 0, nRead); } buffer.Flush(); read(buffer.ToByteArray()); } catch (IOException e) { } } else { status = STATUS_OPEN_ERROR; } try { inputStream.Close(); } catch (Exception e) { } return status; }
public IImage newImage(string fileName, ImageFormat format) { Bitmap.Config config = null; if (format == ImageFormat.RGB565) { config = Bitmap.Config.RGB_565; } else if (format == ImageFormat.ARGB4444) { config = Bitmap.Config.ARGB_4444; } else { config = Bitmap.Config.ARGB_8888; } var options = new BitmapFactory.Options(); options.InPreferredConfig = config; InputStream @in = null; Bitmap bitmap; try { @in = assets.Open(assetsPrefix + fileName); bitmap = BitmapFactory.DecodeStream(@in, null, options); if (bitmap == null) { throw new SystemException("Couldn't load bitmap from asset '" + fileName + "'"); } } catch (IOException e) { throw new SystemException("Couldn't load bitmap from asset '" + fileName + "'"); } finally { if (@in != null) { try { @in.Close(); } catch (IOException e) { } } } if (bitmap.GetConfig() == Bitmap.Config.RGB_565) { format = ImageFormat.RGB565; } else if (bitmap.GetConfig() == Bitmap.Config.ARGB_4444) { format = ImageFormat.ARGB4444; } else { format = ImageFormat.ARGB8888; } return(new AndroidImage(bitmap, format)); }
/// <exception cref="System.IO.IOException"></exception> public override void Close() { @in.Close(); }
/// <exception cref="System.Exception"/> public virtual void Start() { ClassLoader cl = Thread.CurrentThread().GetContextClassLoader(); Runtime.SetProperty(KMSConfiguration.KmsConfigDir, kmsConfDir); FilePath aclsFile = new FilePath(kmsConfDir, "kms-acls.xml"); if (!aclsFile.Exists()) { InputStream @is = cl.GetResourceAsStream("mini-kms-acls-default.xml"); OutputStream os = new FileOutputStream(aclsFile); IOUtils.Copy(@is, os); @is.Close(); os.Close(); } FilePath coreFile = new FilePath(kmsConfDir, "core-site.xml"); if (!coreFile.Exists()) { Configuration core = new Configuration(); TextWriter writer = new FileWriter(coreFile); core.WriteXml(writer); writer.Close(); } FilePath kmsFile = new FilePath(kmsConfDir, "kms-site.xml"); if (!kmsFile.Exists()) { Configuration kms = new Configuration(false); kms.Set(KMSConfiguration.KeyProviderUri, "jceks://file@" + new Path(kmsConfDir, "kms.keystore" ).ToUri()); kms.Set("hadoop.kms.authentication.type", "simple"); TextWriter writer = new FileWriter(kmsFile); kms.WriteXml(writer); writer.Close(); } Runtime.SetProperty("log4j.configuration", log4jConfFile); jetty = CreateJettyServer(keyStore, keyStorePassword, inPort); // we need to do a special handling for MiniKMS to work when in a dir and // when in a JAR in the classpath thanks to Jetty way of handling of webapps // when they are in the a DIR, WAR or JAR. Uri webXmlUrl = cl.GetResource("kms-webapp/WEB-INF/web.xml"); if (webXmlUrl == null) { throw new RuntimeException("Could not find kms-webapp/ dir in test classpath"); } bool webXmlInJar = webXmlUrl.AbsolutePath.Contains(".jar!/"); string webappPath; if (webXmlInJar) { FilePath webInf = new FilePath("target/" + UUID.RandomUUID().ToString() + "/kms-webapp/WEB-INF" ); webInf.Mkdirs(); new FilePath(webInf, "web.xml").Delete(); InputStream @is = cl.GetResourceAsStream("kms-webapp/WEB-INF/web.xml"); OutputStream os = new FileOutputStream(new FilePath(webInf, "web.xml")); IOUtils.Copy(@is, os); @is.Close(); os.Close(); webappPath = webInf.GetParentFile().GetAbsolutePath(); } else { webappPath = cl.GetResource("kms-webapp").AbsolutePath; } WebAppContext context = new WebAppContext(webappPath, "/kms"); if (webXmlInJar) { context.SetClassLoader(cl); } jetty.AddHandler(context); jetty.Start(); kmsURL = new Uri(GetJettyURL(jetty), "kms"); }
public override void Run() { try { byte[] buf = new byte[BUFFER_SIZE]; int interruptCounter = 0; for (; ;) { try { if (interruptCounter > 0) { dst.Flush(); interruptCounter--; } if (done) { break; } int n; try { n = src.Read(buf); } catch (ThreadInterruptedException) { interruptCounter++; continue; } if (n < 0) { break; } bool writeInterrupted = false; for (; ;) { try { dst.Write(buf, 0, n); } catch (ThreadInterruptedException) { writeInterrupted = true; continue; } // set interrupt status, which will be checked // when we block in src.read if (writeInterrupted) { Interrupt(); } break; } } catch (IOException) { break; } } } finally { try { src.Close(); } catch (IOException) { } // Ignore IO errors on close try { dst.Close(); } catch (IOException) { } } }
public virtual void Close() { InputStream.Close(); }
private static string convertStreamTostring(InputStream inputStream) { /* * To convert the InputStream to string we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a stringBuilder * and returned as string. */ BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); string line = null; try { while ((line = reader.ReadLine()) != null) { sb.Append(line + "\n"); } } catch (IOException e) { e.PrintStackTrace(); } finally { try { inputStream.Close(); } catch (IOException e) { e.PrintStackTrace(); } } return sb.ToString(); }
public override void Close() { mInputStream.Close(); }
protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request) { object fullBody = null; Exception error = null; HttpResponse response = null; try { Log.V(Log.TagSync, "%s: RemoteRequest executeRequest() called, url: %s", this, url ); if (request.IsAborted()) { Log.V(Log.TagSync, "%s: RemoteRequest has already been aborted", this); RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted" , this, request)), response); return; } Log.V(Log.TagSync, "%s: RemoteRequest calling httpClient.execute", this); response = httpClient.Execute(request); Log.V(Log.TagSync, "%s: RemoteRequest called httpClient.execute", this); // add in cookies to global store try { if (httpClient is DefaultHttpClient) { DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient; this.clientFactory.AddCookies(defaultHttpClient.GetCookieStore().GetCookies()); } } catch (Exception e) { Log.E(Log.TagRemoteRequest, "Unable to add in cookies to global store", e); } StatusLine status = response.GetStatusLine(); if (Utils.IsTransientError(status) && RetryRequest()) { return; } if (status.GetStatusCode() >= 300) { Log.E(Log.TagRemoteRequest, "Got error status: %d for %s. Reason: %s", status.GetStatusCode (), request, status.GetReasonPhrase()); error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase( )); } else { HttpEntity temp = response.GetEntity(); if (temp != null) { InputStream stream = null; try { stream = temp.GetContent(); fullBody = Manager.GetObjectMapper().ReadValue <object>(stream); } finally { try { stream.Close(); } catch (IOException) { } } } } } catch (IOException e) { Log.E(Log.TagRemoteRequest, "io exception", e); error = e; // Treat all IOExceptions as transient, per: // http://hc.apache.org/httpclient-3.x/exception-handling.html Log.V(Log.TagSync, "%s: RemoteRequest calling retryRequest()", this); if (RetryRequest()) { return; } } catch (Exception e) { Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this); error = e; } Log.V(Log.TagSync, "%s: RemoteRequest calling respondWithResult. error: %s", this , error); RespondWithResult(fullBody, error, response); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected void implCloseChannel() throws java.io.IOException protected internal override void ImplCloseChannel() { @in.Close(); Open = false; }